【问题标题】:Problem setting the layout_gravity on a button using LayoutParams使用 LayoutParams 在按钮上设置 layout_gravity 时出现问题
【发布时间】:2011-09-24 05:53:00
【问题描述】:

我正在向 ListActivity 动态添加一个按钮。如下:

setContentView(R.layout.listview_singlegrey);
LayoutInflater inflater = (LayoutInflater)this.getSystemService
  (Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linear = (LinearLayout) findViewById(R.id.list_comment);
Button btAddComment = (Button)inflater.inflate(R.layout.bt_yellow,null);
FrameLayout.LayoutParams lyp1 = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
lyp1.gravity = Gravity.RIGHT;
btAddComment.setLayoutParams(lyp1);     
btAddComment.setText("Añadir comentario");

列表视图的线性布局是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent" android:orientation="vertical"
        android:layout_height="fill_parent" android:id="@+id/list_comment"
        android:paddingLeft="10dp" android:paddingRight="10dp" android:background="@drawable/fondomain">    
    <ListView android:id="@+id/android:list" android:listSelector="@android:color/transparent"
          android:layout_width="fill_parent" android:layout_height="fill_parent"
          android:divider="@layout/linedivider" android:dividerHeight="10px"
          android:cacheColorHint="#0000" android:paddingTop="10dp"           
          />
</LinearLayout>

我正在充气的按钮的布局是:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
     style="@style/wrapfill"         
     android:background="@layout/selectoryellowbutton" android:layout_gravity="right" android:padding="10dp"
     android:textSize="16px" android:text="Añadir comentario" android:textStyle="bold" android:textColor="@color/darkergray">
</Button>

如您所见,我尝试在代码和按钮中设置 layout_gravity 参数,但它们都不起作用。我仍然在屏幕左侧显示按钮。似乎布局参数不起作用。但是,如果我将 fill_parent 设置为宽度,我会得到整个屏幕上的按钮,并且我希望按钮包裹文本并对齐到屏幕的右侧。

【问题讨论】:

  • 试试这个,创建 Framelayout,将按钮添加为子视图(framelayout.addView(child)),然后在 framelayout 上设置 layoutgravity。
  • 看起来不错!但是列表视图隐藏了按钮:(
  • 你可以动态设置Margins而不是Gravity。

标签: android button layoutparams


【解决方案1】:

您的ButtonListView 包含在LinearLayout 中,android:layout_gravity 属性应与FrameLayout 作为父视图一起使用,不要将FrameLayout.LayoutParams lyp1 设置为按钮的布局参数,

尝试设置您的根LinearLayoutandroid:gravity="right" 或将您的按钮嵌套在另一个LinearLayout 中,重力设置为正确,您可以通过稍后在膨胀布局上调用findViewById 轻松获取按钮实例

【讨论】:

  • 我也在线性布局中使用了 layout_gravity。看看thinkandroid.wordpress.com/2010/01/14/…
  • 当时效果不佳,因为需要引入新布局以将图标定位在右侧,并且 TextViewandroid:layout_gravity 属性对 LinearLayout 重力无效默认为左
猜你喜欢
  • 2016-07-20
  • 2019-04-04
  • 2012-10-16
  • 2013-09-02
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
相关资源
最近更新 更多