Activity内で画面遷移をする方法

Androidで画面遷移をする場合、ActivityをIntentで呼び出す、という方法が一般的。
ただ、Activityを起動すると、それなりに時間がかかってしまったり、トランジションやBackボタンの動作などがホームの設定で規定差れてしまったりなど、不都合もある。

ここではレイアウトを切り替えることで、画面遷移をしているように見せる方法考えてみる。

レイアウトの変更

ただ単純にレイアウトを変更するだけであれば、setContentView()でできる。
ボタンクリックでmainからsubに切り替えるのは以下のような感じ。

onCreate() {
  setContentView(R.layout.main);

  main_button = (Button) findViewById(R.id.button1);
  main_button.setOnClickListener(new OnClickListener(){  
             @Override  
             public void onClick(View v) {  
                 setContentView(R.layout.sub);
             }
         });
}

レイアウト内の要素をプログラムから触りたい場合

次に、subからmainへの切り替えを考える。

setContentView()をしたあとにfindViewById()をすれば良さそうだが、下記コードでsub_buttonはnullが返る。

  setContentView(R.layout.sub);
  sub_button = (Button)findViewById(R.id.button2);

これはActivity.findViewByIdの下記の仕様の通り。onCreate内でprocessしたXMLファイルのみにしか使えない。

Finds a view that was identified by the id attribute
from the XML that was processed in onCreate(Bundle).

代わりに、Layoutを明示的にinflateして、View.findViewById()を使う。

LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View testView = layoutInflater.inflate(R.layout.test, null, false);
setContentView(testView);
Button sub_button = (Button)testView.findViewById(R.id.button2);

あとはmainのときと同様にListnerを登録するなどできる。