簡體   English   中英

如何將onOptionsItemSelected項目ID從主要活動傳遞給另一個活動

[英]how to pass onOptionsItemSelected item id from Main activity to another activity

我想將itemId從主要活動傳遞到另一個活動。 現在我寫了如下代碼,但我不想這樣,只是我想在選擇選項時將itemId從此活動傳遞給另一個活動。 在另一個活動中,我將編寫開關盒選項。

這是我的代碼:

 public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);


        switch(item.getItemId()) {
            case android.R.id.home:mDrawerToggle.onOptionsItemSelected(item);



            case R.id.action_settings:SettingsFragment fragmentS = new SettingsFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragmentS).commit();
                break;

    }

    return super.onOptionsItemSelected(item);
    }

使用意圖在活動之間傳遞數據。

Intent intent = new Intent(current.this, Next.class);
intent.putExtra("itemid", item.getItemId());
startActivity(intent);

並在其他活動中。

 String itemId= getIntent().getStringExtra("itemid");
 switch(itemId)
 {
   ...
  }

從您的代碼看來,您想要將值從一個片段傳遞到另一個片段。 如果是這樣,您應該編輯問題。 俗話說,您希望將價值從一項活動傳遞到另一項活動。 我正在按片段回答。

做這個

switch(item.getItemId()) {
    case android.R.id.home:
        mDrawerToggle.onOptionsItemSelected(item);

    case R.id.action_settings:
        SettingsFragment fragmentS = new SettingsFragment();
        Bundle args = new Bundle();
        args.putInt("ItemID", item.getItemId());
        fragmentS.setArguments(args);
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragmentS).commit();
        break;
}

在其他片段中獲取這樣的值

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    int itemId = getArguments().getInt("ItemID");    
    return inflater.inflate(R.layout.fragment, container, false);
}

那么,您實際上想將數據傳遞給片段嗎?

在進行片段事務之前嘗試添加:

Bundle bundle = new Bundle();
bundle.putInt("id", tem.getItemId());
fragmentS.setArguments(bundle);

暫無
暫無

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

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