簡體   English   中英

子活動 onClick 在父 Class 中觸發

[英]Subactivity onClick Firing in Parent Class

我在 ActivityGroup 的子活動中遇到了 onClick 處理程序的問題。

我正在使用以下方式啟動 StoreActivity:

Intent storeIntent = new Intent(this, StoreActivity.class);
storeIntent.putExtra(StoreActivity.INTENT_STORE_ID, storeId);

View newVeiw = getLocalActivityManager().startActivity("StoreActivity", storeIntent).getDecorView();
setContentView(newVeiw);

Log.e("DEBUG", "current activity: " + getLocalActivityManager().getCurrentActivity().toString());

在 StoreActivity 布局中,我有一個按鈕,它定義了一個 onClick 方法。 然而,出於某種原因,它試圖在啟動 StoreActivity 的父 class 中調用它。 啟動活動時我做錯了什么嗎? 上面 Log.e 的 output 說 StoreActivity 是當前活動,所以我對為什么會發生這種情況有點迷茫。 我可以通過在 StoreActvity 的代碼中為按鈕定義一個 onClickListener 來解決這個問題,但如果可能的話,我想避免這種情況。

我認為這是因為您從父活動而不是子活動調用 setContentView。 為什么不直接在意圖中啟動活動並在新活動中設置內容視圖? 它會簡單得多。

嘗試這個:

Intent storeIntent = new Intent(this, StoreActivity.class);
storeIntent.putExtra(StoreActivity.INTENT_STORE_ID, storeId);
startActivity(storeIntent);

然后在 StoreActivity.java 中執行:

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   View newVeiw = getLocalActivityManager().startActivity("StoreActivity", storeIntent).getDecorView();

    setContentView(newView); //not sure if this would work, would probably be easier to put your xml layout file in here.
}

好的,我已經解決了這個問題。 該問題與任何此代碼無關。 我的活動有一個共同的基礎 class,因為我不小心把充氣機做成了 singleton。 This meant that all inflated layouts belonged to the first class that created that singleton instance which happened to be the class that was incorrectly receiving the onClick event. 刪除 singleton 解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM