How to Start Main Activity Again
When you complete the previous lesson, you lot have an app that shows an activity that consists of a single screen with a text field and a Ship button. In this lesson, you add some code to the MainActivity
that starts a new action 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'south called when the Send push button is tapped:
-
In the file app > java > com.instance.myfirstapp > MainActivity, add the following
sendMessage()
method stub:Kotlin
form MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } /** Called when the user taps the Send button */ fun sendMessage(view: View) { // Practice something in response to push } }
Coffee
public class MainActivity extends AppCompatActivity { @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) { // Exercise something in response to button } }
You might run into an error considering Android Studio cannot resolve the
View
class used as the method argument. To clear the error, click theView
annunciation, identify your cursor on information technology, and then press Alt+Enter, or Option+Enter on a Mac, to perform a Quick Fix. If a menu appears, select Import course. - Return to the activity_main.xml file to call the method from the push:
- Select the push in the Layout Editor.
- In the Attributes window, locate the onClick property and select sendMessage [MainActivity] from its drop-down listing.
At present when the button is tapped, the organization calls the
sendMessage()
method.Take note of the details in this method. They're required for the system to recognize the method as compatible with the
android:onClick
attribute. Specifically, the method has the following characteristics:- Public access.
- A void or, in Kotlin, an implicit unit of measurement return value.
- A
View
every bit the only parameter. This is theView
object yous clicked at the stop of Step one.
- Next, fill in this method to read the contents of the text field and deliver that text to another action.
Build an intent
An Intent
is an object that provides runtime binding between divide components, such every bit two activities. The Intent
represents an app'south intent to exercise something. Y'all tin can use intents for a wide variety of tasks, but in this lesson, your intent starts another activity.
In MainActivity
, add the EXTRA_MESSAGE
abiding and the sendMessage()
code, as shown:
Kotlin
const val EXTRA_MESSAGE = "com.example.myfirstapp.Message" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Packet?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } /** Called when the user taps the Ship push 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, bulletin) } startActivity(intent) } }
Java
public class MainActivity extends AppCompatActivity { public static concluding String EXTRA_MESSAGE = "com.case.myfirstapp.MESSAGE"; @Override protected void onCreate(Packet savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** Called when the user taps the Send button */ public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.course); EditText editText = (EditText) findViewById(R.id.editTextTextPersonName); String bulletin = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
Await Android Studio to run into Cannot resolve symbol errors again. To articulate the errors, press Alt+Enter, or Option+Render on a Mac. Y'all should end up with the following imports:
Kotlin
import androidx.appcompat.app.AppCompatActivity import android.content.Intent import android.os.Packet 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 fault notwithstanding remains for DisplayMessageActivity
, but that's okay. You fix information technology in the adjacent department.
Here'due south what's going on in sendMessage()
:
-
The
Intent
constructor takes 2 parameters, aContext
and aForm
.The
Context
parameter is used get-go because theActiveness
class is a subclass ofContext
.The
Grade
parameter of the app component, to which the arrangement delivers theIntent,
is, in this case, the activeness to first. -
The
putExtra()
method adds the value ofEditText
to the intent. AnIntent
tin acquit data types as key-value pairs chosen extras.Your fundamental is a public abiding
EXTRA_MESSAGE
because the side by side activity uses the fundamental to retrieve the text value. Information technology'southward a skillful practice to define keys for intent extras with your app'south packet name equally a prefix. This ensures that the keys are unique, in case your app interacts with other apps. - The
startActivity()
method starts an example of theDisplayMessageActivity
that's specified by theIntent
. Adjacent, you need to create that form.
Create the second activity
To create the 2d action, follow these steps:
- In the Project window, right-click the app binder and select New > Activity > Empty Activity.
- In the Configure Action window, enter "DisplayMessageActivity" for Activity Name. Go out all other backdrop set up to their defaults and click Finish.
Android Studio automatically does iii things:
- Creates the
DisplayMessageActivity
file. - Creates the layout file
activity_display_message.xml
, which corresponds with theDisplayMessageActivity
file. - Adds the required
<activity>
element inAndroidManifest.xml
.
If you lot run the app and tap the button on the first activity, the second activity starts simply is empty. This is because the 2d activity uses the empty layout provided by the template.
Add a text view
The new activity includes a blank layout file. Follow these steps to add a text view to where the bulletin appears:
- Open the file app > res > layout > activity_display_message.xml.
- Click Enable Autoconnection to Parent in the toolbar. This enables Autoconnect. Run across figure 1.
- In the Palette panel, click Text, drag a TextView into the layout, and drop information technology near the summit-center of the layout so that information technology snaps to the vertical line that appears. Autoconnect adds left and right constraints in club to place the view in the horizontal eye.
- Create one more than constraint from the meridian of the text view to the top of the layout, so that information technology appears every bit shown in effigy 1.
Optionally, yous can make some adjustments to the text style if you expand textAppearance in the Common Attributes panel of the Attributes window, and change attributes such as textSize and textColor.
Display the message
In this stride, you lot modify the 2nd activity to display the message that was passed by the first activeness.
-
In
DisplayMessageActivity
, add the following code to theonCreate()
method:Kotlin
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_display_message) // Become the Intent that started this activity and excerpt the cord val bulletin = intent.getStringExtra(EXTRA_MESSAGE) // Capture the layout's TextView and set the string as 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 string Intent intent = getIntent(); String bulletin = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); // Capture the layout's TextView and set the string every bit its text TextView textView = findViewById(R.id.textView); textView.setText(bulletin); }
-
Press Alt+Enter, or Option+Return on a Mac, to import these other needed classes:
Kotlin
import androidx.appcompat.app.AppCompatActivity import android.content.Intent import android.bone.Bundle import android.widget.TextView
Java
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.bone.Bundle; import android.widget.TextView;
Add upward navigation
Each screen in your app that's not the chief entry signal, which are all the screens that aren't the abode screen, must provide navigation that directs the user to the logical parent screen in the app's bureaucracy. To do this, add an Up button in the app bar.
To add an Up button, you need to declare which action 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 it with the following:
<activity android:proper name=".DisplayMessageActivity" android:parentActivityName=".MainActivity"> <!-- The meta-data tag is required if y'all support API level 15 and lower --> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </action>
The Android system now automatically adds the Upwards button to the app bar.
Run the app
Click Employ Changes in the toolbar to run the app. When it opens, type a bulletin in the text field and tap Send to see the message appear in the second activity.
That's it, you've built your outset Android app!
To continue to acquire the basics about Android app development, become dorsum to Build your commencement app and follow the other links provided at that place.
Source: https://developer.android.com/training/basics/firstapp/starting-activity
0 Response to "How to Start Main Activity Again"
Post a Comment