私が想像する唯一の方法は次のとおりです。
- 各ボタンを独自のレイアウト ファイルに配置します。
- 関数の結果に基づいて、対応するものを膨らませます。
- ビューに追加します。
サンプルコード:
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
、いつでもレイアウトからボタンを削除し、ランダムに選択された新しいボタンを膨張させることができます。
お役に立てれば!