kingemeka
kingemeka

Reputation: 69

how to link a new activity in android studio using a clickable text

Please how do I link a new activity from my main activity using a clickable text. I have set the text to clickable from my main.xml but I don't know how to call the new activity from my MainActivity.java class. I know I have to use this code "textView.setOnClickListener(new View.OnClickListener());" I found in a similar question, but I don't know how and where to place it on my MainActivity.java class so that it calls a the next activity I named display

Upvotes: 0

Views: 2719

Answers (1)

Andrew Senner
Andrew Senner

Reputation: 2509

Check out Intent. You use these to start new activities or services within your application.

You're correct in that you have to assign an OnClickListener interface to your text, after you made it clickable. In the interface's onClick() method you would need to do something like this.

For example:

@Override
public void onClick(View v) {
    // Create the intent which will start your new activity.
    Intent newActivityIntent = new Intent(MainActivity.this, NewActivity.class);

    // Pass any info you need in the next activity in your
    // intent object.
    newActivityIntent.putExtra("aString", "some_string_value");
    newActivityIntent.putExtra("anInteger", some_integer_value);

    // Start the new activity.
    startActivity(newActivityIntent);
}

In the next activity, you can retrieve the intent used to start it, so that you'll have access to the data you passed from the first activity, like so:

@Override
public void onCreate(Bundle savedInstanceState) {
    // Get the intent that started this activity.
    Intent startingIntent = getIntent();

    // Retrieve the values.
    String aString = startingIntent.getStringExtra("aString");
    Integer anInteger = startingIntent.getIntExtra("anInteger", 0); // 2nd param is the default value, should "anInteger" not exist in the bundle.

    // Use the values to your hearts content.
}

Hope that helps.

Upvotes: 1

Related Questions