【问题标题】:Android determine which button was click to start an activityAndroid确定单击哪个按钮以启动活动
【发布时间】: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());

【问题讨论】:

    标签: android button android-activity components


    【解决方案1】:

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

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

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

    你有几个选择:

    1) 使用来自IntentBundle

    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”方法。我只是将字符串用于演示目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      相关资源
      最近更新 更多