我需要为Textview设置布局重力,这是在Relative布局中, 我是通过xml做的,但是如何以编程方式进行呢?
<Relativelayout>
<Textview
android:gravity="left"
android:layout_gravity="center_vertical|right"/>
</Relativelayout>
我需要以编程方式设置gravity和layout_gravity。
答案 0 :(得分:1)
试试这个
指定视图在
RelativeLayout
中的定位方式。包含视图的相对布局使用这些布局参数的值来确定在屏幕上放置视图的位置。如果视图未包含在相对布局中,则忽略这些属性。
示例代码
TextView textView=findViewById(R.id.spn);
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)textView.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
textView.setLayoutParams(layoutParams);
答案 1 :(得分:1)
试试这个:
RelativeLayout relativeLayout=new RelativeLayout(this);
TextView textView=new TextView(this);
RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
textView.setLayoutParams(layoutParams);
relativeLayout.addView(textView);
答案 2 :(得分:0)
创建layoutParams对象,在那里定义引力并将其设置为textview。
答案 3 :(得分:0)
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;
button.setLayoutParams(params);
将LinearLayout.LayoutParams
替换为RelativeLayout.LayoutParams
答案 4 :(得分:0)
Textview tx= new Textview(this);
RelativeLayout.LayoutParams params = new Relative.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.center_vertical;
tx.setLayoutParams(params):
或其他选项检查此链接 https://android--code.blogspot.com/2015/05/android-textview-layout-gravity.html