如何在Android中为TextView设置LAYOUT_GRAVITY?

时间:2012-05-15 08:03:37

标签: android android-layout textview

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

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

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

使用完之后,我的文字就会停留在左上角的标准位置。 宽度:FILL_PARENT或重力代码都不做任何事情。

5 个答案:

答案 0 :(得分:13)

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL)

答案 1 :(得分: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);

答案 2 :(得分: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);

答案 3 :(得分:0)

Android set the gravity for a TextView programmatically 你看到过这个回应吗?

TextView tv  = (TextView) findViewById(R.layout.text_view);   
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);

答案 4 :(得分:-1)

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

  • 您需要使用父布局的LayoutParams(因此布局_ 重力)
  • 例如,如果父是FrameLayout do:

    FrameLayout.LayoutParams layoutParams = 
        new FrameLayout.LayoutParams(textView.getLayoutParams());
    layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;
    textView.setLayoutParams(layoutParams);