简体   繁体   中英

Align Imageview in LinearLayout by code

the question is simple, i am creating a imageview dynamically using code.

ImageView btnSend = new ImageView (this);

and add it to a LinearLayout, the problem is that I want to leave right-aligned

how to do that?

Thanks in advance

Try using LayoutParams:

LinearLayout rootLayout = (LinearLayout)findViewById(R.id.root_layout);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;

ImageView btnSend = new ImageView (this); 
btnSend.setLayoutParams(params);
rootLayout.addView(btnSend);

The only problem is that I don't remember if params.gravity sets the content gravity or layout_gravity. Layout_gravity is what you're wanting to change in this instance.

You have to call setGravity() on LinearLayout:

yourLinLay.setGravity(Gravity.RIGHT);

or in XML:

<LinearLayout android:gravity="right">

http://developer.android.com/reference/android/widget/LinearLayout.html#setGravity%28int%29 http://developer.android.com/reference/android/view/Gravity.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM