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

Posted

技术标签:

【中文标题】Android确定单击哪个按钮以启动活动【英文标题】:Android determine which button was click to start an activity 【发布时间】:2011-08-16 04:43:53 【问题描述】:

我有一个将从父活动启动的活动,但子活动的行为将根据在父活动中单击按钮来确定。

我一直在尝试确定调用了哪个 button.onClick 方法来启动子活动,但是很遗憾,我失败了。

具体来说,我一直专注于使用 ComponentName 并将其展平为字符串,但每次我尝试这样做时,都会收到空指针异常。

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());

【问题讨论】:

【参考方案1】:

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

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

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

你有几个选择:

1) 使用来自Intent 的Bundle:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) 创建一个新的捆绑包

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);

注意: Bundle 对所有原始类型、Parcelable 和 Serializable 都有“get”和“put”方法。我只是将字符串用于演示目的。

【讨论】:

以上是关于Android确定单击哪个按钮以启动活动的主要内容,如果未能解决你的问题,请参考以下文章

Android:单击按钮时默认选项卡式活动不会启动

按下“确定”按钮后,Android 相机活动不会返回到我的应用程序

仅当在 Android 中单击按钮后条件为真时才启动 Activity

如何在按钮单击时启动新活动

处理菜单项点击事件 - Android

单击按钮时如何将文本视图从一件事切换到另一件事 - Android