Align Imageview in LinearLayout by code

我只是一个虾纸丫 提交于 2019-12-10 20:39:47

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4616445/align-imageview-in-linearlayout-by-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!