ふわふわぷかぷか

最近はイラレとAeにはまってます。

新しく開いた画面を閉じる。

前回は、インテントを使って画面遷移をし、新しい画面を開く方法でした。

今回は、その開いた画面を閉じて最初の画面に戻す方法です。

 

main.xml(最初の画面)は、テキストビューを1つだけ増やしました。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#ffffff">

        <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="最初の画面" />
       
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ボタン" />

</LinearLayout>

 Activityは同じなので省略します。

 

Sub.xml(新しく開く画面)は、ボタンを1つ追加しました。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#ffffff" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="新しい画面ができたよ!" />
   
    <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="戻る" />
   
</LinearLayout>

 

次にSubActivityですが、finish();で画面を閉じることができます。

public class SubActivity extends Activity implements OnClickListener {
Button button1;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub);

button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}

public void onClick(View v) {
if(v == button1){
finish();}
}}

 これで、画面を閉じることができます。

f:id:fuwafuwapukapuka:20140226205814j:plain → f:id:fuwafuwapukapuka:20140226205824j:plain

インテントで新しい画面を何個も開くと、開いた順番にどんどん画面が重ねられていくようです。

「finish();」で閉じられる画面は、今開いている画面だけのようです。(いくつも閉じるように設定すればできるようですが難しそう…)

全ての画面を一度に閉じる(アプリを終了する)には、「this.moveTaskToBack(true);」を使います。Activityの「finish();」の部分を変えるだけで出来るようになります。

コピペではじめるAndroidゲームプログラミング

コピペではじめるAndroidゲームプログラミング