ActivityのWidgetを動的に入れ替えるちょっとだけ面倒でない方法
Androidのアプリを作るとき、ひとつのActivityで、状況に応じてWidgetを動的に入れ替えたい場合があります。 一度に全部のボタンは不要で、他のコンテンツの表示領域を広く確保したいときなどですね。
よく、
と説明されているのを見ますが、実際、コード中でインスタンスを生成して見た目に関する設定をするのって、それなりに面倒な作業じゃないかなと思いまして、onCreate
でButton
を動的に生成し、コンテナにaddView
する
Button
自体は、main_activity.xml
の、しかるべきコンテナ(LinearLayout
など)に、全部配置しておき、見た目の設定はビジュアルに済ませて、実行時に、removeAllViews
で、一旦全部削除すればよいのです。
以下のような感じ(実際に動かしているコードではないのでお気をつけて)
main_activity.xml
<LinearLayout id="@+id/linearLayout" ... > <Button id="@+id/button1" ... /> <Button id="@+id/button2" ... /> <Button id="@+id/button3" ... /> <Button id="@+id/button4" ... /> </LinearLayout>
MainActivity.java
public class MainActivity extends Activity { ViewGroup linearLayout1 = null; Button button1 = null; Button button2 = null; Button button3 = null; Button button4 = null; @Override protected void onCreate(Bundle savedInstanceState) { // find container widget linearLayout1 = (ViewGroup)findViewById(R.id.linearLayout1); // find each buttons button1 = (Button)findViewById(R.id.button1); button2 = (Button)findViewById(R.id.button2); button3 = (Button)findViewById(R.id.button3); button4 = (Button)findViewById(R.id.button4); changeState(0); // // ... // } private changeState(int state) { linearLayout1.removeAllViews(); switch(state) { case 0: linearLayout1.addView(button1); linearLayout1.addView(button2); break; case 1: linearLayout1.addView(button3); linearLayout1.addView(button4); break; } // // ... // } }
LinearLayout
の中身を均等割り付けするように設定しておけば、それなりにお手軽。
派手じゃないけど、堅実な動きですよ。
以下、GitHubのGist試用
ひとつのGist中で、ファイルの順番は入れ替えられないのかな。あと、なんでJavaは8タブにしかならないのか。
« 打ち上げじゃなく反省会 | トップページ | 仕事と趣味とランニング »
「プログラミング」カテゴリの記事
- 自分で書いたコードが大好き(2020.09.20)
- NPMのヨロコビ(2020.05.14)
- VanilaJS は必須科目(2019.02.25)
- MZ-700フルJavaScriptエミュレータ v1.0.6 をリリース(2019.01.26)
- 戦々恐々GitHub vs BitBucket(2019.01.08)
コメント