自定义TextView上的保证金

tom*_*tom 6 android margin textview

我检查了很多答案,但迄今为止没有人帮忙.

我正在尝试扩展android的TextView并在代码中设置此自定义视图的边距,因为我将在按钮按下和类似的事情上实例化它们.它被添加到LinearLayout.那就是我得到的:

public class ResultsView extends TextView {
    public ResultsView(Context context) {
        super(context);
        LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layout.setMargins(15, 15, 15, 15);
        setLayoutParams(layout);
    }
}
Run Code Online (Sandbox Code Playgroud)

任何地方都没有任何保证金

编辑:我可能想添加,如果我在xml中分配一个边距值,它确实有效.

Mar*_*res 17

我认为问题在于,当您尝试添加边距时,layoutparams尚未设置,为什么不尝试在ResultsView类中重写此方法:

       protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            MarginLayoutParams margins = MarginLayoutParams.class.cast(getLayoutParams());
            int margin = 15;
            margins.topMargin = margin;
            margins.bottomMargin = margin;
            margins.leftMargin = margin;
            margins.rightMargin = margin;
            setLayoutParams(margins);
        };
Run Code Online (Sandbox Code Playgroud)

并删除构造函数中的代码,这样边距将被应用,直到我们确定我们有一个视图的布局对象,希望这有助于

问候!