如何将ImageView与LinearLayout的右侧以编程方式对齐android

and*_*ser 7 android

我想以编程方式将ImageView对齐到LinearLayout的右侧.我怎么能这样做.

aho*_*der 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>
Run Code Online (Sandbox Code Playgroud)

编程

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);
}
Run Code Online (Sandbox Code Playgroud)


Bot*_*acz 5

你可以试试这个:

ImageView view = (ImageView)findViewById(R.id.imageView);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.LEFT;
Run Code Online (Sandbox Code Playgroud)

但你应该用RelativeLayout而不是LinearLayout.