2016-06-10 87 views
-2

我是新來的片段。我在第一個片段中添加了兩個編輯文本,我想將該編輯文本數據發送到第二個片段。一個片段與另一個片段之間的通信

我正在使用一個包,但它在第二個片段中打印null。

誰能告訴我如何發送數據到其他片段?

第一個片段

nextt.setOnClickListener(new Button.OnClickListener() { 
     @Override 
     public void onClick(View _view) { 
      int viewId = _view.getId(); 
      FragmentTransaction ft; 
      switch (viewId) { 
       case R.id.Button1: 
        FragmentManager fm = getFragmentManager(); 
        ft = fm.beginTransaction(); 
        SecondFrag secondFrag = new SecondFrag(); 
        Bundle bundle = new Bundle(); 
        bundle.putInt("deviceInst",viewId); 
        secondFrag.setArguments(bundle); 
        ft.replace(R.id.total_frame_content, secondFrag); 
        ft.addToBackStack(null); 
        ft.commit(); 
        break; 
      } 
     } 
    }); 

在第二個片段

 @Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    View v = inflater.inflate(R.layout.second_new, container, false); 
    String value = getArguments().getString("deviceInst"); 
    System.out.println("TTTT"+ value); 
+1

一定要仔細閱讀本https://developer.android.com/training/basics/fragments/communicating.html – Raghunandan

+0

你路過詮釋和獲得在字符串檢查你的代碼 –

+0

@Ashwini Bhat..if我想在這種情況下傳遞字符串和整數? – pruthvi

回答

2

在你的第一個片段中,你傳遞一個int作爲參數。

bundle.putInt("deviceInst",viewId);

,然後在你的第二個片段您嘗試使用 getArguments().getString("deviceInst")

這將無法得到這樣的說法,所以讓你通過,你需要使用getArguments().getInt("deviceInst")

參數爲了封裝所需的數據,一個好的提示是在需要數據的片段中有一個靜態的newInstance()方法。

這是關於它的一篇文章。

https://plus.google.com/+AndroidDevelopers/posts/bCD7Zvd945d

+0

和for傳遞字符串? – pruthvi

+0

'bundle.putString(「deviceInst」,viewId);' – raxelsson

+0

如果我把viewid放在傳遞字符串中顯示錯誤 – pruthvi

0

您需要更改像

int value = getArguments().getInt("deviceInst"); 

,而不是

String value = getArguments().getString("deviceInst"); 
0

你需要在你的代碼以下更改。

bundle.putString("deviceInst",editText.getText().toString()); 

然後在你的第二個片段則可以通過使用

getArguments().getString("deviceInst") 

這裏EDITTEXT是在第一個片段編輯文本的情況下獲得這樣的說法。

+0

Bro如何傳遞listview數據? – pruthvi

+0

listView。setOnItemClickListener(),然後onItemClick從您提供的數組列表/數據源中檢索數據。 –

0
As you have passed int in the bundle, you need to use getInt() in your receiver fragment. 
For example: 
SecondFrag secondFrag = new SecondFrag(); 
        Bundle bundle = new Bundle(); 
        bundle.putInt("deviceInst",viewId); 
        secondFrag.setArguments(bundle); 
getFragmentManager().beginTransaction().add(R.id.total_frame_content, secondFrag).commit(); 

In receiver fragment 
    String value = getArguments().getInt("deviceInst");