Android learning route (5) enable another Activity

Source: Internet
Author: User

Android learning route (5) enable another Activity

After completing the previous course, you already have an application. This application shows an activity that contains a text box and a button (a separate interface ). In this course, you will add some code to MainActivity so that you can jump to another activity when you click Send.

Send Response button

To respond to the button clicking event, openfragment_main.xmlLayout the file, and thenAdd to elementandroid:onClickAttribute:

Thisandroid:onClickAttribute value,"sendMessage"Is the name of a method in your activity. When you click the button, this method is called.

OpenMainActivityClass, add the corresponding method:

/** Called when the user clicks the Send button */public void sendMessage(View view) {    // Do something in response to button}

To allow the system to matchandroid:onClickThe method corresponding to the Method Name of the assigned value. The signature must be displayed strictly. (The signature must be exactly as shown.) the method must be as follows:

  • Is Public
  • The return type is void.
  • Only oneViewType parameter (it indicatesView)

    Next, you need to fill up this method. To read the content in the text box, and then pass the content to another activity.

    Construct an Intent

    IntentIs an object that is bound at runtime by two separated components (for example, two activities.IntentIndicates that an application "intends to do something ". You can use intent to do many things, but it is most commonly used to open another activity.

    InsendMessage()CreateIntentTo enableDisplayMessageActivityActivity:

    Intent intent = new Intent(this, DisplayMessageActivity.class);

    This requires pilot ImportIntentClass:

    import android.content.Intent;

    TIPS:In Eclipse, you can use Ctrl + Shift + O to import unimported classes (Cmd + Shift + O in Mac ).

    The constructor used here contains two parameters:

    • The first parameter isContext(Used herethisBecauseActivityClass isContextSubclass)
    • The second parameter is to be passedIntentThe application component class (in this example, the activity to be opened) sends intent to other applications.

      The intent created in this application is a clear intent, because izhgeIntentSpecifies the explicit application component that intent should provide. The Intent can also be concealed. In some cases, the intent does not specify components, however, it allows applications installed on devices to respond to the specified Intent as parameters. For more information, see the course: Interacting with Other Apps.

      Tip: DisplayMessageActivityWill cause an error, because you are using an IDE such as Eclipse, it will find that this class does not exist. Ignore this error and you will immediately create this class.

      Intent can not only open another activity, but also carry a bundle containing data. InsendMessage()Internal method, usefindViewById()To obtainEditTextElement, and add its value to the intent:

      Intent intent = new Intent(this, DisplayMessageActivity.class);EditText editText = (EditText) findViewById(R.id.edit_message);String message = editText.getText().toString();intent.putExtra(EXTRA_MESSAGE, message);

      Tip:You need to importandroid.widget.EditText. You need to defineEXTRA_MESSAGEConstant.

      IntentA set of different types of key-value pairs called extars can be carried.putExtra()The first parameter is the key name, and the second parameter is the value.

      To enable the next activity to find extra data, you should use public constants to assign values to your intent key. Therefore, add a definition in the MainActivity header.EXTRA_MESSAGE:

      public class MainActivity extends ActionBarActivity {    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";    ...}

      When your application interacts with other applications, using the package name of your application as the key defined by intent extras is a good choice.

      Open the second Activity

      To open an activity, callstartActivity()Method, andIntentAfter the system accepts the call, the specified intentActivity.

      In the new code, the completesendMessage()The method should be as follows:

      /** Called when the user clicks the Send button */public void sendMessage(View view) {    Intent intent = new Intent(this, DisplayMessageActivity.class);    EditText editText = (EditText) findViewById(R.id.edit_message);    String message = editText.getText().toString();    intent.putExtra(EXTRA_MESSAGE, message);    startActivity(intent);}

      Now you need to createDisplayMessageActivityClass to continue working.

      Create the second Activity

      Figure 1. Create Activity wizard in Eclipse

      Use Eclipse to create an activity:

      1. ClickNew.
      2. In the displayed window, openAndroidFolder and selectAndroid Activity <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Examples/examples + ILXju/examples + oaM8bGk + zO7C + examples/LV38rH1NrKudPDw/zB7tDQuaS + 36 OsxMfDtNTaPGNvZGU + release/CvM/release + release/qOsyOe5 + release/WoaM8bGk + zazR + release/release + wP3W0LK7u + release/zJvrX0oaM8bGk + release/release + VXA8L2VtPiDKwrz + o6yxo7PWy/release + release/ydbY08O1xMSjv + mho7j8tuC52NPaRnJhZ21lbnS1xNDFz6KjrMfrsum/release "note"> Tip:If you are not using the latest ADT plug-in, your activity may look different. Make sure that you have installed the latest ADT plugin to complete this course.

        DisplayMessageActivityThe class should now be like this:

        public class DisplayMessageActivity extends ActionBarActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_display_message);        if (savedInstanceState == null) {            getSupportFragmentManager().beginTransaction()                .add(R.id.container, new PlaceholderFragment()).commit();        }    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    /**     * A placeholder fragment containing a simple view.     */    public static class PlaceholderFragment extends Fragment {        public PlaceholderFragment() { }        @Override        public View onCreateView(LayoutInflater inflater, ViewGroup container,                  Bundle savedInstanceState) {              View rootView = inflater.inflate(R.layout.fragment_display_message,                      container, false);              return rootView;        }    }}

        If the IDE you are using is not EclipseDisplayMessageActivityClass to the above Code.

        AllActivityMust be implementedonCreate()The system will call this method when creating a new activity instance. This method is requiredsetContentView()Method to specify the layout of the activity, and also the place where you want to initialize the activity component.

        Tip:If you use a non-Eclipse IDE, your project does not containactivity_display_messageLayout file. It doesn't matter. You will update this method immediately and do not need to use this layout file.

        Add a title string

        If you use Eclipse, you can adjust it to the next section (next section), because the Template already provides the title string.

        If you are using another IDE, add the title of the new activitystrings.xmlFile:

                 
                      ...    
                  
                   My Message
                  
                 
        Add a new Activity to the Manifest File

        All activities must be declared in the manifest file,AndroidManifest.xml, UseElement.

        When you are using Eclipse, it creates a default object. If you are not using Eclipse, you need to add the list entity by yourself. As shown below:

            ...            
                     

        android:parentActivityNameDeclares the name of the parent activity of the activity in the application logic level. The system will implement default navigation Behaviors Based on this value, such as Up navigation in Android4.1 or later. You can also use the Support Library package, and then Add this value to the element.

        Tip:Your Android SDK should have the latest Support package. It is included in the ADT Bundle, but if you are not using Eclipse, you need to install it in the Adding Platforms and Packages step. When you use an Eclipse template, the Support package is automatically added to your project. If you are not using Eclipse, You need to manually add this Library Island to your project and follow the setting up the Support Library operation to return here.

        If you use Eclipse for development, you can run the program now, but nothing will happen. When the Send button is clicked, it will jump to the new activity, but it uses the default "Hello World" interface. You will update the activity immediately and use a custom text view to display it. If you are not using Eclipse and cannot compile it, don't worry.

        Receive Intent

        EachActivityWill beIntentCall, whether it is a user operation or not. You can callgetIntent()Method to obtain the intent that enables your activity, or the data contained in it.

        InDisplayMessageActivityClassonCreate()Method, get throughMainActivityPassed information:

        Intent intent = getIntent();String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        Display Information

        To display the information on the screen, you must createTextViewControl, and then usesetText()Method. Then addTextViewAs the Root View of the activity layout.

        CompleteonCreate()The method should be as follows:

        @Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    // Get the message from the intent    Intent intent = getIntent();    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);    // Create the text view    TextView textView = new TextView(this);    textView.setTextSize(40);    textView.setText(message);    // Set the text view as the activity layout    setContentView(textView);}

        Now you can run your application. After it is started, enter the information in the text box and click send. The entered information will appear in the second activity.

        Figure 2. Two activities in the app run on android 4.4

        You have created your first application!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.