如何在Android中编程将ImageView对齐到LinearLayout的右侧

7
我想在LinearLayout编程方式下将ImageView对齐到右侧。我该怎么做?

1
LinearLayout不支持这个功能。你可以在LinearLayout中包裹一个RelativeLayout来包含你的ImageView。 - WSBT
2个回答

24
你不能这样做。线性布局不是这样工作的。请使用RelativeLayout代替。
XML
<RelativeLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

以编程方式

public void makeView(Context context) {
    RelativeLayout rl = new RelativeLayout(context);
    TextView tv = new TextView(context);
    tv.setText("Hello, World");

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams
            (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

    rl.addView(tv, lp);
}

好的,我如何以编程方式将TextView添加到RelativeLayout并右对齐。 - androiduser
我不想使用XML布局。我想以编程方式显示,因为数据是动态的。 - androiduser

5
您可以尝试以下方法:
ImageView view = (ImageView)findViewById(R.id.imageView);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.LEFT;

但是你应该使用RelativeLayout而不是LinearLayout

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接