1

我需要一个在左边和右边。所有配置都应该通过代码完成。截屏:

在此处输入图像描述

代码:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.overview);
    loadData();
    TableLayout tl = (TableLayout)findViewById(R.id.tl);
    TableRow tr = new TableRow(this);
    TableRow tr2 = new TableRow(this);
    tr.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    //tr2.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    //tr2.setLayoutParams(new ViewGroup.LayoutParams(L., LayoutParams.WRAP_CONTENT));
    TextView tv = new TextView(this);
    TextView tv2 = new TextView(this);
    //tv.se
    tv.setGravity(Gravity.LEFT);
    tv2.setGravity(Gravity.RIGHT);
    tv.setText("Test");
    tv2.setText("Test");
    //tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f));
    //tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
    tv2.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f));
    //tv.setTextSize(50);
    //tv2.setTextSize(50);
    tr.addView(tv);
    tr.addView(tv2);
    //tl.addView(tr);
    //setContentView(tl);
    tl.addView(tr, new TableLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    }

布局:

<TableLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/tl"
  android:stretchColumns="*">
</TableLayout>
4

2 回答 2

2

LayoutParams 被视图用来告诉他们的父母他们想要如何布局。Android 中定义了大约 13 种不同类型的 LayoutParam。例如。LinearLayout.Layoutparams、ViewGroup.LayoutParams、ActionBar.LayoutParams 等。

因此,如果将 TextView 添加到 LinearLayout,则意味着 LinearLayout 是 TextView 的父级,因此在为 textView 定义布局参数时,应使用 LinearLayout.LayoutParams 而不是 ViewGroup.LayoutParams

在您的情况下,您正在向表格行添加两个文本视图,所以很明显您应该使用 TableRow.LayoutParams

所以替换这一行

tv2.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f)); 

tv2.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f)); 

为电视写类似的 文章 这是我在这个网站上的第一篇文章。希望它会有所帮助:)

于 2011-10-04T09:29:53.000 回答
0

我认为你必须使用:

  android:stretchColumns="0,1"

很好的例子可以在这里找到

做这个:

从 tv2 布局参数中删除 1f。

tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

这可以根据给定的链接解决您的问题。

于 2011-10-04T06:54:44.183 回答