Caglar Onbasi Caglar Onbasi - 2 months ago 9
Android Question

How to change an activitiy's strings with clicked TextView

I have two activities,

MainActivity
and
SecondActivity
. In
MainActivity
I have 10
TextViews
listed. And all of them clickable. I want to go to
SecondActivity
when any of these
TextViews
are clicked and second
Activity
shows text about clicked
TextView
.

For example:

MainActivity
textViews:

1) Mercedes

2) BMW

3) Audi

4) Porsche

When Mercedes clicked, in
SecondActivity
a text about mercedes and on
SecondActivity
a back button. When BMW clicked on
MainActivity
SecondActivity
open again but text about BMW.

I hope I could explain.

Answer

MainActivity:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textview = (TextView) findViewById(R.id.bmw);
    textview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent (this,SecondActivity.class);
            intent.putExtra("data","BMW");

            startActivity(intent);
        }
    });

     //similarly send data to next activity
  }
}

SecondActivity:

public class SecondActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_layout);

    Intent intent=getIntent();
    String message = intent.getStringExtra("data");

    TextView textview = (TextView) findViewById(R.id.textView);

    textView.setText(message);

   }
}