Android 确定单击哪个按钮来启动活动
我有一个将从父活动启动的活动,但子活动的行为将根据在父活动中单击按钮来确定。
我一直在尝试确定调用哪个 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());
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 failed.
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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要作为 Extras 传递一个自定义值,该值将告诉您哪个按钮启动了该活动。这必须在调用活动中完成,而不是在新活动中完成。
这是一个示例,可以帮助您
第一个上下文(可以是 Activity/Service 等)
您有几个选项:
1) 使用 Bundle 来自 Intent:
2) 创建一个新的 Bundle
3) 使用 putExtra() Intent 的快捷方法
新建上下文(可以是 Activity/Service 等)
注意: Bundles 对所有基本类型、Parcelables 和 Serializeds 都有“get”和“put”方法。我只是将字符串用于演示目的。
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:
2) Create a new Bundle
3) Use the putExtra() shortcut method of the Intent
New Context (can be Activity/Service etc)
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.