Android确定单击哪个按钮以启动活动

Bry*_*emp 2 android components button android-activity

我有一个将从父活动开始的活动,但子活动的行为将基于在父活动中单击按钮来确定.

我一直试图确定调用哪个button.onClick方法来启动子活动,但是,我失败了.

具体来说,我一直专注于使用ComponentName并将其展平为一个字符串,但每次我尝试这样做时,我都会得到一个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());
Run Code Online (Sandbox Code Playgroud)

Pen*_*m10 5

您需要将Extras作为自定义值传递,该值将告诉您哪个按钮启动了该活动.这必须在调用活动而不是新活动中完成.

这是一个可以帮助您的示例

第一个上下文(可以是活动/服务等)

你有几个选择:

1)使用意向:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  
Run Code Online (Sandbox Code Playgroud)

2)创建一个新的Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
Run Code Online (Sandbox Code Playgroud)

3)使用Intent 的putExtra()快捷方法

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
Run Code Online (Sandbox Code Playgroud)

新上下文(可以是活动/服务等)

Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
     String value = myIntent.getExtras().getString(key);
}
Run Code Online (Sandbox Code Playgroud)

注意: Bundles对所有基本类型,Parcelables和Serializables都有"get"和"put"方法.我只是将Strings用于演示目的.