I have an activity that will be started from a parent activity, but the behavior of the subactivity will be determined based upon with button is clicked in the parent activity.
I have been trying to determine which button.onClick method was called to start the subactivity, but alas, I have fai开发者_运维技巧led.
Specifically, I have been focused on using the ComponentName and flattening it to a string, but every time I attempt to do this, I get a Null Pointer Exception.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subactivity);
ComponentName callingActivity = SubActivity.this.getCallingActivity();
TextView listtype = (TextView) findViewById(R.id.subactivity_listtype);
listtype.setText(callingActivity.flattenToString());
You need to pass as Extras a custom value that will tell you which button started the activity. This must be done in the calling activity not the new one.
Here is a sample that can help you
First Context (can be Activity/Service etc)
You have a few options:
1) Use the Bundle from the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) Create a new Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
3) Use the putExtra() shortcut method of the Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
New Context (can be Activity/Service etc)
Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(key);
}
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
精彩评论