Accessing members in one Activity from another
开发者_如何学运维I'm going for a tabbed layout for my application, and I'm having a little trouble. I have the main Activity, and then I have the sub activities (one for each tab). In one sub activity, I have a TextView set as a public member of the activity. Using the main activity, how could I call .setText()
on the TextView in the sub activity? Thanks!
to achieve that is sending extras in your Main Activity intent, receive in your SubActivity and set text in your TextView.
Source::
Bundle bundle = new Bundle();
bundle.putString("Title","Accessing members in one Activity from another");
Intent newIntent = new Intent(MainActivity.this, SubActivity.class);
newIntent.putExtras(bundle);
startActivity(newIntent);
Target::
Bundle bundle = getIntent().getExtras();
String ReceivedTitle = bundle.getString("Title");
TextView.setText(ReceivedTitle);
One option would be, to pass the text string that you want to set on the sub activity using putExtras when you launch the sub activity Intent. And then, in oncreate or start, do the setText.
Intent myIntent = new Intent();
myIntent.setClassName("com.mypackage", "com.mypackage.SubActivity");
myIntent.putExtra("com.mypackage.MyText", "Hello World");
startActivity(myIntent);
精彩评论