Load Activity Again and Kill Old Activity Android
When you complete the previous lesson, you accept an app that shows an activity that consists of a unmarried screen with a text field and a Send push button. In this lesson, you add some code to the MainActivity that starts a new activity to display a bulletin when the user taps the Send button.
Respond to the Send button
Follow these steps to add together a method to the MainActivity class that'southward called when the Send button is tapped:
-
In the file app > java > com.example.myfirstapp > MainActivity, add the following
sendMessage()method stub:Kotlin
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Parcel?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } /** Chosen when the user taps the Send button */ fun sendMessage(view: View) { // Do something in response to button } }Java
public course MainActivity extends AppCompatActivity { @Override protected void onCreate(Parcel savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** Called when the user taps the Send push */ public void sendMessage(View view) { // Practise something in response to push } }You might see an error because Android Studio cannot resolve the
Viewcourse used as the method statement. To clear the mistake, click theViewdeclaration, identify your cursor on it, and then press Alt+Enter, or Pick+Enter on a Mac, to perform a Quick Fix. If a menu appears, select Import grade. - Render to the activity_main.xml file to call the method from the button:
- Select the button in the Layout Editor.
- In the Attributes window, locate the onClick property and select sendMessage [MainActivity] from its driblet-downwards list.
Now when the button is tapped, the organisation calls the
sendMessage()method.Accept note of the details in this method. They're required for the system to recognize the method as compatible with the
android:onClickaspect. Specifically, the method has the following characteristics:- Public access.
- A void or, in Kotlin, an implicit unit return value.
- A
Viewas the only parameter. This is theViewobject you clicked at the end of Stride 1.
- Side by side, fill in this method to read the contents of the text field and evangelize that text to another activity.
Build an intent
An Intent is an object that provides runtime bounden between split components, such as two activities. The Intent represents an app's intent to do something. You can employ intents for a wide variety of tasks, just in this lesson, your intent starts another activity.
In MainActivity, add the EXTRA_MESSAGE constant and the sendMessage() lawmaking, every bit shown:
Kotlin
const val EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE" form MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } /** Chosen when the user taps the Send button */ fun sendMessage(view: View) { val editText = findViewById<EditText>(R.id.editTextTextPersonName) val bulletin = editText.text.toString() val intent = Intent(this, DisplayMessageActivity::class.java).employ { putExtra(EXTRA_MESSAGE, message) } startActivity(intent) } } Java
public class MainActivity extends AppCompatActivity { public static terminal String EXTRA_MESSAGE = "com.example.myfirstapp.Message"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** Called when the user taps the Send push button */ public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.editTextTextPersonName); Cord bulletin = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } } Expect Android Studio to encounter Cannot resolve symbol errors again. To articulate the errors, press Alt+Enter, or Option+Return on a Mac. You should terminate upwardly with the following imports:
Kotlin
import androidx.appcompat.app.AppCompatActivity import android.content.Intent import android.os.Parcel import android.view.View import android.widget.EditText
Java
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Packet; import android.view.View; import android.widget.EditText;
An error withal remains for DisplayMessageActivity, but that's okay. You ready information technology in the next department.
Hither's what'southward going on in sendMessage():
-
The
Intentconstructor takes two parameters, aContextand aGrade.The
Contextparameter is used first because theActivityclass is a subclass ofContext.The
Classparameter of the app component, to which the system delivers theIntent,is, in this example, the activity to offset. -
The
putExtra()method adds the value ofEditTextto the intent. AnIntentcan conduct data types as cardinal-value pairs called extras.Your central is a public constant
EXTRA_MESSAGEconsidering the adjacent activity uses the key to call back the text value. Information technology's a practiced practice to ascertain keys for intent extras with your app'south package name as a prefix. This ensures that the keys are unique, in case your app interacts with other apps. - The
startActivity()method starts an instance of theDisplayMessageActivitythat's specified by theIntent. Next, yous demand to create that class.
Create the second activeness
To create the 2nd activity, follow these steps:
- In the Projection window, right-click the app folder and select New > Activity > Empty Activity.
- In the Configure Activity window, enter "DisplayMessageActivity" for Activity Proper name. Get out all other properties set to their defaults and click Finish.
Android Studio automatically does iii things:
- Creates the
DisplayMessageActivityfile. - Creates the layout file
activity_display_message.xml, which corresponds with theDisplayMessageActivityfile. - Adds the required
<activity>element inAndroidManifest.xml.
If y'all run the app and tap the push on the first activity, the second activity starts but is empty. This is considering the second activeness uses the empty layout provided past the template.
Add together a text view
The new activeness includes a blank layout file. Follow these steps to add together a text view to where the message appears:
- Open the file app > res > layout > activity_display_message.xml.
- Click Enable Autoconnection to Parent
in the toolbar. This enables Autoconnect. See figure 1. - In the Palette panel, click Text, drag a TextView into the layout, and drop it nigh the summit-center of the layout so that it snaps to the vertical line that appears. Autoconnect adds left and right constraints in order to place the view in the horizontal center.
- Create one more constraint from the pinnacle of the text view to the summit of the layout, so that it appears every bit shown in figure 1.
Optionally, you can make some adjustments to the text style if yous aggrandize textAppearance in the Common Attributes panel of the Attributes window, and modify attributes such as textSize and textColor.
Display the message
In this pace, yous modify the 2nd activity to display the message that was passed by the first activity.
-
In
DisplayMessageActivity, add the following lawmaking to theonCreate()method:Kotlin
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_display_message) // Go the Intent that started this activity and excerpt the string val bulletin = intent.getStringExtra(EXTRA_MESSAGE) // Capture the layout's TextView and set the string every bit its text val textView = findViewById<TextView>(R.id.textView).apply { text = message } }Java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); // Get the Intent that started this activity and extract the cord Intent intent = getIntent(); String bulletin = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); // Capture the layout's TextView and set the string as its text TextView textView = findViewById(R.id.textView); textView.setText(message); } -
Printing Alt+Enter, or Option+Render on a Mac, to import these other needed classes:
Kotlin
import androidx.appcompat.app.AppCompatActivity import android.content.Intent import android.os.Bundle import android.widget.TextView
Java
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView;
Add together upward navigation
Each screen in your app that's not the chief entry point, which are all the screens that aren't the home screen, must provide navigation that directs the user to the logical parent screen in the app's hierarchy. To do this, add together an Up button in the app bar.
To add an Up push, you need to declare which activity is the logical parent in the AndroidManifest.xml file. Open the file at app > manifests > AndroidManifest.xml, locate the <activity> tag for DisplayMessageActivity, and replace information technology with the following:
<activeness android:name=".DisplayMessageActivity" android:parentActivityName=".MainActivity"> <!-- The meta-data tag is required if you back up API level 15 and lower --> <meta-data android:proper noun="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activeness>
The Android system now automatically adds the Up push button to the app bar.
Run the app
Click Apply Changes in the toolbar to run the app. When it opens, type a message in the text field and tap Ship to see the message appear in the second activity.
That's it, you've built your first Android app!
To continue to learn the nuts about Android app evolution, get dorsum to Build your first app and follow the other links provided at that place.
Source: https://developer.android.com/training/basics/firstapp/starting-activity
0 Response to "Load Activity Again and Kill Old Activity Android"
Post a Comment