1

LinearLayoutが必要な要件があり、このレイアウトのセルごとに、異なる背景があります。これは設計者の例です。

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

XMLだけでこれを達成できる方法はありますか、それとも実行時に実行する必要がありますか?線形レイアウトのセル数を取得して、この数で作業するにはどうすればよいですか?

どうもありがとう、フェリペ

4

2 に答える 2

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 に答える
1

追加するアイテムの数がわからないため、XML を介して静的にではなく動的に TextView を追加する必要があります。最初にデバイス画面の高さを取得してから、次の式に基づいて TextViews を親コンテナーに追加する必要があります。

TextViews の数 = (ディスプレイの高さ) / (1 つのテキスト ビューの高さ)

ここで必要なのは、TextView を動的に作成し、それらをループ内の親コンテナーに追加することだけです。

これのサンプルコードは次のとおりです。

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 に答える