articles

Home / DeveloperSection / Articles / A Display Message on ButtonClick in a textView

A Display Message on ButtonClick in a textView

A Display Message on ButtonClick in a textView

Anonymous User 29894 10-Nov-2014

Display Message on ButtonClick in a textView(By starting another activity) in Android

In the previous article “Building simple user interface in Android”, we have created a simple GUI interface having a Text Field and a button, now we implement some more functionality into it. This post is the extension of the same.

Functionality: We fill the Text Field with our message, and the message will be

display on a new Text view when we click the Send button.

So, for our implements, we need to add some more code to MainActivity that starts a new activity when the user clicks the Send button.

Respond to the Send button:

To respond to the button’s on-click event, open the activity_main.xml layout file and add the android : onClick attribute to the <Button> element :

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"
/>

The android:onClick attribute’s value, "sendMessage", is the name of a method in

our activity that the system calls when the user clicks the button.

Open the MainActivity class (located in the project's src/ directory) and add the

corresponding method:

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

In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:

  •      Be public
  •      Have a void return value
  •      Have a View as the only parameter (this will be the View that was clicked)

Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity. 

Build an Intent

An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but most often they’re used to start another activity.

Inside the sendMessage() method, create an Intent to start an activity called DisplayMessageActivity:

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

This requires that you import the Intent class:   

import android.content.Intent;The constructor used here takes two parameters:
  • The Context as its first parameter (this is used because the Activity class is a subclass of Context)
  • The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started)
  • An intent not only allows us to start another activity, but it can carry a bundle of data to the activity as well. Inside the sendMessage() method, use findViewById() to get the EditText element and add its text value to the intent
  • We now need an import statement for android.widget.EditText and also, we need to define the EXTRA_MESSAGE constant as well.
  • An Intent can carry a collection of various data types as key-value pairs called extras. The putExtra() method takes the key name in the first parameter and the value in the second parameter.
  • In order for the next activity to query the extra data, we should define the key for our intent's extra using a public constant.
  • So add the EXTRA_MESSAGE definition to the top of the MainActivity class:
public class 
MainActivity extends ActionBarActivity
{
public final static String EXTRA_MESSAGE="com.example.myHelloAndroid.MESSAGE";     ...
}

**It's generally a good practice to define keys for intent extras using your app's package name as a prefix. This ensures they are unique, in case your app interacts with other apps

Start the Second Activity:

To start an activity, call startActivity() and pass it to your Intent. The system receives this call and starts an instance of the Activity specified by the Intent. 

With this new code, the complete sendMessage() method that's invoked by the Send button now looks like this:

/** 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 create the DisplayMessageActivity class in order for this to work.
Create the Second Activity
  • Click New in the toolbar.
  • In the window that appears, open the Android folder and select Android Activity. Click Next.
  • Select BlankActivity and click Next.   
  • Activity Name: DisplayMessageActivity 
  • Layout Name: activity_display_message 
  • Fragment Layout Name: fragment_display_message 
  • Title: My Message 
  • Hierarchial Parent: com.example.myfirstapp.MainActivity 
  • Navigation Type: None
  • Click Finish. 

Display Message on ButtonClick in a textView(By starting another activity) in Android     

Add the title string

If you used Eclipse, you can skip to the next section, because the template provides

the title string for the new activity.

If you're using an IDE other than Eclipse, add the new activity's title to the

strings.xml file:

<resources>
    ...
    <string name="title_activity_display_message">My Message</string>
</resources>

Add it to the manifest

All activities must be declared in your manifest file, AndroidManifest.xml, using an

<activity> element.

When you use the Eclipse tools to create the activity, it creates a default entry. If

you're using a different IDE, you need to add the manifest entry yourself. It should

look like this:

<application ... >
    ...
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity"
>
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity"
/>
    </activity>
</application>

Receive the Intent

Every Activity is invoked by an Intent, regardless of how the user navigated there.

You can get the Intent that started your activity by calling getIntent() and retrieve

the data contained within it.

In the DisplayMessageActivity class’s onCreate() method, get the intent and extract

the message delivered by MainActivity:

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

Display the Message

To show the message on the screen, create a TextView widget and set the text

using setText(). Then add the TextView as the root view of the activity’s layout by

passing it to setContentView().

The complete onCreate() method for DisplayMessageActivity now looks like this:

@Override
public 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 =newTextView(this);     textView.setTextSize(40);     textView.setText(message);
    // Set the text view as the activity layout     setContentView(textView);
}

You can now run the app. When it opens, type a message in the text field, click

Send, and the message appears on the second activity.

         Display Message on ButtonClick in a textView(By starting another activity) in Android

This post is referred from Google docs Starting Another Activity


I am a content writter !

Leave Comment

Comments

Liked By