TextView layout_gravity不能编程工作



我一直在寻找,并找到了许多可能的解决方案,在布局中居中的textview。但没有一个对我有用。我的textview是在一个表布局,这是由以下xml描述:

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/schedule_main_holder">
    <TableLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:stretchColumns="0"
      android:id="@+id/schedule_table_entry">
   </TableLayout>
</LinearLayout>

我正在做的是做一个新的TableRow,然后添加一个TextView和一个ListView到它…但textview必须垂直居中。我正在做的是:

TableRow row = new TableRow(this);
        TextView tview = new TextView(this);
        tview.setText("Wednesday");
        TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL);
        tview.setLayoutParams(layoutParams);
        row.addView(tview);

问题是,TextView总是在单元格的顶部,而不是在中间,因为它应该。我已经尝试了组合的混合(即使是在另一个响应中描述的framayout方法),我不能让textview在表格单元格中居中。

Thanks in advance

首先重力有两种类型。我想你用的是常规重力,而不是布局。其次,你也可以在xml中创建视图,然后使用膨胀器,然后添加。这也给了更干净的代码。

编辑:所以你懒得去尝试布局膨胀器并听取建议,下面是代码:

main。xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="0"
android:id="@+id/schedule_table_entry">
</TableLayout>

myrow.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
    android:id="@+id/text"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_gravity="center" />
</TableRow>

TestActivity

public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LayoutInflater inflater = getLayoutInflater();
    TableRow row = (TableRow) inflater.inflate(R.layout.myrow, null);
    TextView text = (TextView) row.findViewById(R.id.text);
    text.setText("I did all your work... smart even");
    TableLayout table = (TableLayout) findViewById(R.id.schedule_table_entry);
    table.addView(row);
}

最新更新