Android: in intent, start a new Activity explicitly through startActivity(Intent intent)

Keywords: Android xml encoding Java

Intent: intention. It is generally used to start a new Activity. It can be divided into two types: explicit intent and implicit intent

To display Intent is to directly use "class name" to specify which activity to start: Intent intent = new Intent (this, activity. Class); where activity.class is to specify the activity to start

For example, there are two newly created activities: MainActivity and DemoActivity. Now, we will jump from MainActivity to DemoActivity

 

Activity main.xml is as follows:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout
 3     xmlns:android="http://schemas.android.com/apk/res/android"
 4     xmlns:app="http://schemas.android.com/apk/res-auto"
 5     xmlns:tools="http://schemas.android.com/tools"
 6     android:layout_width="match_parent"
 7     android:layout_height="wrap_content"
 8     android:orientation="vertical"
 9     android:layout_gravity="center"
10     android:gravity="center"
11     tools:context="com.hs.example.exampleapplication.MainActivity">
12 
13     <Button
14         android:id="@+id/btn_demoActivity"
15         android:layout_width="wrap_content"
16         android:layout_height="match_parent"
17         android:text="Jump to DemoActivity"/>
18 
19 </LinearLayout>

 

MainActivity.java code is as follows:

 1 public class MainActivity extends AppCompatActivity implements View.OnClickListener{
 2 
 3     Button btn_intent;
 4 
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9 
10      
11         btn_intent = this.findViewById(R.id.btn_demoActivity);
12         btn_intent.setOnClickListener(this);
13 
14     }
15 
16     @Override
17     public void onClick(View view) {
18        
19         Intent intent = new Intent(MainActivity.this,DemoActivity.class);
20         startActivity(intent);
21 
22 
23     }
24 }

 

Click the display button after running to jump to the new activity

 

If you need to transfer data to a new activity:

 

1 @Override
2 17     public void onClick(View view) {
3 18        
4 19         Intent intent = new Intent(MainActivity.this,DemoActivity.class);
5 20         intent.putExtra(String name , String value);  //Passing data as key value pairs
6 21 
7 22         startActivity(intent);
8 23     }

 

Parameter acquisition method passed:

 

1 Intent intent = getIntent();
2 
3 String str = intent.getStringExtra("key");         //Read from key Data in
4 int i = intent.getIntExtra("key",0);               //No value defaults to 0

If you want to transfer more data, you can learn about: Bundle

Posted by smsulliva on Thu, 21 Nov 2019 07:07:44 -0800