私は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" />
唯一の変更は、centerHorizontalラインを削除したことです。しかし、これは単純化された例です。
さて、私はアプリを作成したいと思います、それは時々(ランダム関数を使用して)ビューAを使用し、時々ビューBを使用します。
実行時にこの「ビューの切り替え」を行うことは可能ですか? 2つのビューを使用してこのアプリを構築することは可能ですか(ボタンのIDは同じである必要があることに注意してください。ロジックを2回実装したくありません)。
どうもありがとう!
回答:
回答№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
、ただし、何らかのユーザー入力の後)ボタンをレイアウトからいつでも削除して、ランダムに選択された新しいボタンを膨らませることができます。
お役に立てれば!