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());
您需要将Extras作为自定义值传递,该值将告诉您哪个按钮启动了该活动.这必须在调用活动而不是新活动中完成.
这是一个可以帮助您的示例
第一个上下文(可以是活动/服务等)
你有几个选择:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  
2)创建一个新的Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
3)使用Intent 的putExtra()快捷方法
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
新上下文(可以是活动/服务等)
Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
     String value = myIntent.getExtras().getString(key);
}
注意: Bundles对所有基本类型,Parcelables和Serializables都有"get"和"put"方法.我只是将Strings用于演示目的.
| 归档时间: | 
 | 
| 查看次数: | 343 次 | 
| 最近记录: |