LinearLayout与背景不同的单元格?可能?

时间:2012-08-22 16:17:20

标签: android android-linearlayout

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

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

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

非常感谢, 菲利普

2 个答案:

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

答案 1 :(得分:1)

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

  

no 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);
    }
}

}