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:

  1. 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 the View 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.

  2. Return to the activity_main.xml file to call the method from the push:
    1. Select the push in the Layout Editor.
    2. 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 the View object yous clicked at the stop of Step one.
  3. 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, a Context and a Form.

    The Context parameter is used get-go because the Activeness class is a subclass of Context.

    The Grade parameter of the app component, to which the arrangement delivers the Intent, is, in this case, the activeness to first.

  • The putExtra() method adds the value of EditText to the intent. An Intent 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 the DisplayMessageActivity that's specified by the Intent. Adjacent, you need to create that form.

Create the second activity

To create the 2d action, follow these steps:

  1. In the Project window, right-click the app binder and select New > Activity > Empty Activity.
  2. 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 the DisplayMessageActivity file.
  • Adds the required <activity> element in AndroidManifest.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 text view centered at the top of the layout.
Figure 1. The text view centered at the top of the layout.

The new activity includes a blank layout file. Follow these steps to add a text view to where the bulletin appears:

  1. Open the file app > res > layout > activity_display_message.xml.
  2. Click Enable Autoconnection to Parent in the toolbar. This enables Autoconnect. Run across figure 1.
  3. 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.
  4. 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.

  1. In DisplayMessageActivity, add the following code to the onCreate() 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);                  }                
  2. 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.

App opened, with text entered on the left screen and displayed on the right.
Figure 2. App opened, with text entered on the left screen and displayed on the correct.

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.

lampefught1937.blogspot.com

Source: https://developer.android.com/training/basics/firstapp/starting-activity

0 Response to "How to Start Main Activity Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel