【问题标题】:Setting margin and gravity of textview in code doesn't work在代码中设置 textview 的边距和重力不起作用
【发布时间】:2011-06-16 16:12:22
【问题描述】:

如果我只为我的文本视图设置边距,即在线性布局内,一切正常。 如果我只为我的 textview 设置重力,它就可以工作。但是如果我设置了两个属性(重力和边距),重力保持在左边,边距设置成功。

我设置两个属性的代码没有按预期工作:

tv2=new TextView(this);
tv2.setText("Text");
LinearLayout.LayoutParams para=new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT );
para.setMargins(0, 10, 0, 10); //left,top,right, bottom
tv2.setLayoutParams(para);
tv2.setGravity(android.view.Gravity.CENTER_HORIZONTAL);

我必须在代码中构建我的布局,不能使用 xml 文件。

【问题讨论】:

    标签: android layout margin gravity


    【解决方案1】:

    尝试改用这个:

    para.gravity = Gravity.CENTER_HORIZONTAL;
    tv2.setLayoutParams(para);
    
    //the below sets the view's content gravity, not the gravity
    //of the view itself. Since the width is wrap_content, this
    //has no effect.
    //tv2.setGravity(android.view.Gravity.CENTER_HORIZONTAL);
    

    【讨论】:

      猜你喜欢
      • 2016-02-29
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 2015-02-03
      相关资源
      最近更新 更多