Javaバックエンド学Android(2)-intentの使用


本シリーズは『Android第1行コード第2版』読書ノート
一、Intentを使って活動の間を行き来する
前述の記事では、ASのEmpty Activityを使ってHello Worldを体験しました.つまりAndroidにとってActivityが重なっているので、複数のActivityを使うことができます.では、EmptyのActivityを新規作成し、対応するlayoutファイルを作成します.
現在、2つのActivityがMainActivity、SecondActivityとなっています.今完成しなければならない機能はMainActivityにボタンがあり、このボタンをクリックするとSecondActivityに入ることができ、SecondActivityにもボタンがあります.
上記の要件は、2つのActivity間の切り替えを行うことですが、必然的に切り替えと同時に、2つのActivity間でデータをどのように伝達する必要がありますか?ではIntentへの使用が必要です
1.1明示的なIntent
環境準備
first_layout.xml:Button_を定義する1

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button 1">Button>

LinearLayout>

second_layout.xml:Button_を定義する3

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button_3"
        android:text="Button 3">Button>

LinearLayout>

明示的なintentを使用して、1つのActivityから別のActivityに変更できます.
例えばMainActivityでボタンクリックイベントを定義する
public class MainActivity extends AppCompatActivity {
     

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.first_layout);
        Button button1 = (Button)this.findViewById(R.id.button_1);
        button1.setOnClickListener((View view) -> {
     
            //  Intent
            Intent intent = new Intent(this, SecondActivity.class);
            this.startActivity(intent);
        });

    }

}
public Intent(Context packageContext, Class<?> cls) {
     
    mComponent = new ComponentName(packageContext, cls);
}

Intent関数は2つのパラメータを受信します.
  • 最初のパラメータContextはコンテキストで、一般的にthisを使用すると
  • になります.
  • の2番目のパラメータは、起動するターゲットActivity
  • です.
    その後startActivityを使用してActivityを起動します
    1.2暗黙Intentの使用
    暗黙的なIntentを使用すると、どのアクティビティを開始するかは不明ですが、アクティビティにactionとcategory情報を指定します.その後、このIntentを分析し、適切なアクティビティを見つけて起動します.
    上の例ではAndroidManifestですxml定義の情報
    <activity android:name=".SecondActivity">
        <intent-filter>
            <action android:name="com.example.activitytest.ACTION_START" />
    		 
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="com.example.activitytest.MY_CATEGORY" />
        intent-filter>
    activity>
    

    続いてMainActivityで
    public class MainActivity extends AppCompatActivity {
         
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
         
            super.onCreate(savedInstanceState);
            this.setContentView(R.layout.first_layout);
            Button button1 = (Button)this.findViewById(R.id.button_1);
            button1.setOnClickListener((View view) -> {
         
                //    Intent
                Intent intent = new Intent("com.example.activitytest.ACTION_START");      		        
            intent.addCategory("com.example.activitytest.MY_CATEGORY");
            });
        }
    }
    

    Actionラベルは、現在のアクティビティがcomに応答できることを指定する.example.activitytest.ACTION_STARTというアクティビティですが、categoryラベルにはいくつかの追加情報が含まれています.現在のアクティビティがIntentに含まれるcategoryに応答できることをより正確に示しています.actionとcategoryのコンテンツが同時にIntentのコンテンツに一致している場合にのみ、このアクティビティはIntentに応答できます.
    1.3次のアクティビティへのデータの転送
    2つのActivity間の関連付けにはIntentが必要なので、データの転送にもIntentが使用されます.
  • Intent.putExtra(String name,@Nullable String value):Intentにデータ
  • を書き込む
  • Intent.getxxxxxExtra:Intentにデータを取得する
  • もちろん、これらの方法は、異なる金額のデータを転送するためのいくつかのリロード方法です.
    たとえば、MainActivityはSecondActivityにデータを渡す必要があります.
    MainActivity.java
    public class MainActivity extends AppCompatActivity {
         
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
         
            super.onCreate(savedInstanceState);
            this.setContentView(R.layout.first_layout);
            Button button1 = (Button)this.findViewById(R.id.button_1);
            button1.setOnClickListener((View view) -> {
         
                //  Intent
                String data = "Hello SecondActivity";
                Intent intent = new Intent(this, SecondActivity.class);
                intent.putExtra("data", data);
                this.startActivity(intent);
            });
        }
    }
    

    SecondActivity.java
    public class SecondActivity extends AppCompatActivity {
         
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
         
            super.onCreate(savedInstanceState);
            setContentView(R.layout.second_layout);
            //    
            Intent intent = this.getIntent();
            String data = intent.getStringExtra("data");
            Log.d("Intent   " , data);
            //  
            Toast.makeText(this,data, Toast.LENGTH_SHORT).show();
        }
    }
    

    1.4前のアクティビティへのデータの転送
    1つのデータを下に渡すことができる以上、ActivityではstartActivity ForResultメソッドがアクティビティを開始するために使用されますが、このメソッドは、アクティビティが破棄されたときに前のアクティビティに結果を返すことを期待します.startActivity ForResultメソッドは2つのパラメータを受信します
  • Intent:起動したActivity
  • requestCode:コールバック後にデータを判断するためのソース
  • .
    MainActivity.java
    public class MainActivity extends AppCompatActivity {
         
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
         
            super.onCreate(savedInstanceState);
            this.setContentView(R.layout.first_layout);
            Button button1 = (Button)this.findViewById(R.id.button_1);
            button1.setOnClickListener((View view) -> {
         
                Intent intent = new Intent(this, SecondActivity.class);
                this.startActivityForResult(intent, 1);
            });
        }
        
        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
         
            //super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
         
                case 1:
                    if (resultCode == RESULT_OK) {
         
                        String dataReturn = data.getStringExtra("data_return");
                        Toast.makeText(this, dataReturn, Toast.LENGTH_SHORT).show();
                        Log.d("      ", dataReturn);
                    }
                    break;
                default:
            }
        }
    }
    

    SecondActivity.java
    
    public class SecondActivity extends AppCompatActivity {
         
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
         
            super.onCreate(savedInstanceState);
            setContentView(R.layout.second_layout);
            //      
            Button button = (Button) this.findViewById(R.id.button_3);
            button.setOnClickListener((View v) -> {
         
                Intent intent = new Intent();
                intent.putExtra("data_return", "Hello Return");
                //       ,        ,                RESULT_OK  RESULT_CANCELED
                this.setResult(RESULT_OK, intent);
                //    Activity
                this.finish();
            });
        }
    }
    

    また、SecondActivityアクティビティの破棄時に、前のアクティビティのonActivity Resultメソッドを呼び出します.このメソッドでは、破棄アクティビティのデータを取得できます.このメソッドでは、3つのパラメータが導入されます.
  • requestCode:startActivity ForResultに入力int値
  • です.
  • resultCode:結果
  • を返します.
  • data:破棄されたintent
  • また、finish()メソッドでアクティビティを破棄し、ロールバックキーを使用してアクティビティを破棄することもできるので、アクティビティのライフサイクル関数で定義できます.
    SecondActivity.java
        @Override
        public void onBackPressed() {
         
            Intent intent = new Intent();
            intent.putExtra("data_return", "Hello Return");
            this.setResult(RESULT_OK, intent);
            this.finish();
        }