gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:39:33 25 4
gpt4 key购买 nike

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

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

具体来说,我一直专注于使用 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());

最佳答案

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

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

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

您有几个选择:

1) 使用 Bundle来自 Intent :

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) 使用 putExtra() Intent的快捷方式

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);

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

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 对所有原始类型、Parceables 和 Serializables 都有“get”和“put”方法。我只是将字符串用于演示目的。

关于Android确定单击哪个按钮以启动 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5844201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com