4

如何通过代码设置 TextView 的 layout_gravity?

我尝试使用 layoutparams 没有任何好的结果。

new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, Gravity.LEFT | Gravity.CENTER_VERTICAL); 

使用这个之后,我的文本就停留在标准的位置,在左上角。宽度:FILL_PARENT 或重力代码都没有做任何事情。

4

5 回答 5

13
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL)
于 2012-05-15T08:07:03.590 回答
2

您可以使用以下代码在代码中使用重力:

    Button button = (Button) findViewById(R.id.MyButtonId);
    // need to cast to LinearLayout.LayoutParams to access the gravity field
    LayoutParams params = (LayoutParams)button.getLayoutParams(); 
    params.gravity = Gravity.BOTTOM;
    button.setLayoutParams(params);
于 2012-05-15T08:12:07.470 回答
1

Android 以编程方式设置 TextView 的重力 你看到这个响应了吗?

TextView tv  = (TextView) findViewById(R.layout.text_view);   
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
于 2012-05-15T08:13:36.317 回答
0
 layout = (LinearLayout) findViewById(R.id.vendor_detail_lay);
    LinearLayout linearLayout = new LinearLayout(getApplicationContext());
    linearLayout.setOrientation(0);
    txtveiw = new TextView(NewVendorDetailActivity.this);
    txtveiw.setLayoutParams(Gravity.LEFT | Gravity.CENTER_VERTICAL);
    txtveiw.setId(itemId);
    txtveiw.setText(cursor.getString(cursor.getColumnIndex(DataBaseHelper.KEYNAME)));

    linearLayout.addView(txtveiw);
    layout.addView(linearLayout);
于 2012-05-15T08:10:23.740 回答
-1

保留现有布局参数的最佳解决方案:

  • 您需要使用父布局的 LayoutParams(因此layout_gravity
  • 例如,如果父母是 FrameLayout 做:

    FrameLayout.LayoutParams layoutParams = 
        new FrameLayout.LayoutParams(textView.getLayoutParams());
    layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;
    textView.setLayoutParams(layoutParams);
    
于 2017-08-14T13:14:43.580 回答