如何在实例化片段时传递数据,因为我无法覆盖构造函数?

时间:2015-09-27 09:14:24

标签: android android-fragments android-adapter

我有一个FragmentPageAdapter,我希望它使用不同的值而不是各种片段加载相同的片段。 这个值只有1个字符串。我该如何通过?

3 个答案:

答案 0 :(得分:1)

一个关于如何做的简单示例:

// in the adapter
private static final String[] VALUES = { 
   "string 1", 
   "string 2", 
   "string 3", 
   "string 4", 
   "string 5",  };

@Override
public Fragment getItem(int position) {
    MyFrag f = new MyFrag();
    Bundle b = new Bundle();
    b.putString("value", VALUES[position]);
    f.setArguments(b);
    return f;
}

// then in the fragment 
private String value;
public void onCreate(Bundle savedInstanceState) {
   value = getArguments.getString("value");
}

答案 1 :(得分:1)

您应该使用Bundle(片段参数)。见例:

//put yours info to Bundle
Bundle bundl = new Bundle();
bundl.putString("key", "value");
//set bundle to frgments arguments
YoursFragClass frag = new YoursFragClass();
frag.setArguments(bundl);
//add fragment to activity
...

Bundle中的您的信息将显示为Fragments实时循环方法的参数

//then in fragments `onCreate()` or `onCreateView()` you receive this Bundle as argument
public class YoursFragClass extends Fragment {

     public View onCreateView(LayoutInflater inflater,
         ViewGroup containerObject,
         Bundle savedInstanceState){
         //here is your arguments
         Bundle bundle=getArguments(); 

        //here is yours info
        String myString = bundle.getString("key");
        System.out.println(myString); //will show "value" in logCat
     }
}

答案 2 :(得分:1)

您应该使用参数。

它们表示为Bundle,并通过setArguments()设置。请记住,只有在片段附加到活动之前才能设置它们。

为方便起见,您可以为片段创建工厂方法,以隐藏创建包的复杂性:

public class MyFragment extends Fragment {

    public static MyFragment getInstance(<the instantiation parameters here>) {

        // check parameter preconditions
        final Bundle arguments = new Bundle();
        // put parameters into the bundle
        final MyFragment instance = new MyFragment();
        instance.setArguments(arguments);
        return instance;
    }
}

使用参数的另一个好处是,如果正在重新创建片段实例,则会保留它们。