2013-07-19 125 views
5

我检查了很多答案,但目前为止没有任何帮助。自定义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); 
    } 
} 

任何地方都没有保证金的迹象。

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

回答

14

我认为这个问题是,你的时间尝试添加的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); 
     }; 

,并删除您在构造有代码,这样的利润率将被应用,直到我们确信我们有一个布局对象的观点,希望这有助于

商祺!

+0

耶!这真的做到了,谢谢!实际上我曾尝试过类似的方法,但是使用onFinishInflate,这并不奏效。你知道这在演出方面有多好吗?我应该更好地添加一个布尔值来检查我们是否已经设置了一次? – tom

+0

我不认为这是一个巨大的表演影响,但如果你担心它,你可以添加标志只做一次,如果你想... –

+1

我认为你可以逃脱只是修改尺寸传入onLayout()(例如,left + = leftMargin,right - = rightMargin,top + = topMargin,bottom - = bottomMargin,super.onLayout(changed,left,top,right,bottom)); – kcoppock

0

您现在需要将此视图添加到当前正在显示的布局中。你错过了下一步。 所以,现在你需要的东西,如:

currentlayout.addview(View); 
+0

它以XML添加。我可以在LinearLayout中看到textviews,但它们没有空白。 – tom