0

Android アプリがあり、互いに類似した 2 つのビューが必要です。例えば ​​:

    <Button
    android:id="@+id/ok"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:text="OK" />

    <Button
    android:id="@+id/ok"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OK" />

唯一の変更点は、中央の水平線を削除したことです。ただし、これは単純化された例です。

今、私はアプリを作成したいと思っています。

実行時にこの「ビューの切り替え」を行うことは可能ですか? 2 つのビューを使用してこのアプリを構築することは可能ですか (ボタンには同じ ID が必要であることに注意してください。ロジックを 2 回実装したくありません)。

どうもありがとう!

4

1 に答える 1

0

私が想像する唯一の方法は次のとおりです。

  • 各ボタンを独自のレイアウト ファイルに配置します。
  • 関数の結果に基づいて、対応するものを膨らませます。
  • ビューに追加します。

サンプルコード:

button_a.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ok"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:text="OK" />

button_b.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ok"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OK_2" />

あなたの活動:

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

    LayoutInflater inflater = LayoutInflater.from(this);

    Button button;

    if (Math.random() > 0.5) {
        button = (Button) inflater.inflate(R.layout.button_a, null);
    } else {
        button = (Button) inflater.inflate(R.layout.button_b, null);
    }

    /* ...
       Set listeners to the button and other stuff 
       ...
    */

    //find the view to wich you want to append the button
    LinearLayout view = (LinearLayout) this.findViewById(R.id.linearLayout1);

    //append the button
    view.addView(button);
}

これを動的に (つまり、 ではなく、ユーザー入力の後に) 発生させたい場合はonCreate、いつでもレイアウトからボタンを削除し、ランダムに選択された新しいボタンを膨張させることができます。

お役に立てれば!

于 2012-04-28T15:59:05.363 に答える