2016-03-02 89 views
1

我有以下简单代码在内容框架中从一个片段切换到另一个片段。有一种简单的方法可以在下面的代码中传递变量吗?如何通过Android fragmentmanager传递变量

FragmentManager fm = getActivity().getFragmentManager(); 

fm.beginTransaction().replace(R.id.content_frame, new TransactionDetailsFragment()).commit(); 
+1

不知道为什么这被标记为这个问题清楚地说明了fragmentmanager,所引用的答案只涉及一个新的片段类,这对于一个java newb来说是一个差异。然而,接受的答案似乎已经正确承认了这一点。 –

回答

4

您可以使用捆绑:

FragmentManager fm = getActivity().getFragmentManager(); 
Bundle arguments = new Bundle(); 
arguments.putInt("VALUE1", 0); 
arguments.putInt("VALUE2", 100); 

MyFragment myFragment = new Fragment(); 
fragment.setArguments(arguments); 

fm.beginTransaction().replace(R.id.content_frame, myFragment).commit(); 

然后,您检索如下:

public class MyFragment extends Fragment { 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     Bundle bundle = this.getArguments(); 
     if (bundle != null) { 
      int value1 = bundle.getInt("VALUE1", -1); 
      int value2 = bundle.getInt("VALUE2", -1); 
     } 
    } 
} 
1

如何创建TransactionDetailsFragment的参数化构造函数?

fm.beginTransaction().replace(R.id.content_frame, new TransactionDetailsFragment(YOUR_PARAMS)).commit(); 

当您创建new TransactionDetailsFragment(YOUR_PARAMS)作为FragmentTransaction设置了一个param,我想使用的构造是一个不错的选择。

+0

使用这个,但它有一个问题 - 没有noarg构造函数,这个片段不能在xml布局中使用。 – Pavlus

1

或者你可以使用newInstance方法 - 创建片段类像里面的方法:

public static TransactionDetailsFragment newInstance(String param) { 
    TransactionDetailsFragment frag = new TransactionDetailsFragment(); 
    Bundle bund = new Bundle(); 
    bund.putString("paramkey", param); // you use key to later grab the value 
    frag.setArguments(bund); 
    return frag; 
} 

所以要创建你的片段:

TransactionDetailsFragment.newInstance("PASSING VALUE"); 

(这是用来代替你new TransactionDetailsFragment()

然后,例如,在相同的片段的onCreate/onCreateView你得到这样的价值:

String value = getArguments().getString("paramkey");