1

我有一个要求,我需要有一个 LinearLayout,对于这个布局的每个单元格,我会有不同的背景。这是设计师的例子:

http://img823.imageshack.us/img823/1857/untilied.png

有什么方法可以仅通过 XML 实现,还是应该在运行时完成?如何获取线性布局的单元格计数并处理此数字?

非常感谢,费利佩

4

2 回答 2

1

由于您不知道要添加的项目数量,您应该动态添加 TextViews 而不是通过 XML 静态添加。您应该首先获取设备屏幕的高度,然后根据以下公式将 TextViews 添加到父容器:

没有 TextViews = (显示高度) / (一个文本视图的高度)

现在您只需要动态创建 TextViews 并将它们循环添加到父容器中。

这是一个示例代码:

public class DynamicActiviy extends Activity {

/*parent container*/
LinearLayout root;

/*colors*/
Integer[] colors = {R.color.red1,R.color.red2,R.color.red3,R.color.red4,R.color.red5,
        R.color.red6,R.color.red7,R.color.red8,R.color.red9,R.color.red10};

/*text view height*/
final int MAX_HEIGHT = 60;

/*display height*/
int displayHeight;

/*no of text views to be added*/
int noTextViews;

TextView text;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.backs);

    root = (LinearLayout)findViewById(R.id.root);
    displayHeight = getWindowManager().getDefaultDisplay().getHeight();
    noTextViews = displayHeight / MAX_HEIGHT;

    int size = colors.length;
    LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, MAX_HEIGHT);

    for(int i=0; i<noTextViews; i++)
    {
        text = new TextView(this);
        text.setBackgroundResource(colors[i%size]);
        text.setGravity(Gravity.CENTER_VERTICAL);
        text.setPadding(20, 0, 0, 0);
        text.setText(colors[i%size]+ "");
        root.addView(text,lp);
    }
}

}

于 2012-08-22T17:38:01.607 回答
1

您可以在 XML 中为每个 TextView 定义背景。只需使用android:background

http://developer.android.com/reference/android/view/View.html#attr_android:background

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="text"
        android:background="@color/blue" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="text"
        android:background="@color/red" />

</LinearLayout>

要动态更改,您可以执行以下操作:

TextView txtView1 = (TextView) findViewById(R.id.textView1);
txtView1.setBackgroundResource(R.color.green);
于 2012-08-22T16:38:05.730 回答