如何将数据从Adapter传递给Fragment?

时间:2016-07-26 13:43:12

标签: android android-fragments android-adapter

如何在fragmentfinalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { finalHolder.spinner.setSelection(position); selState = finalHolder.spinner.getSelectedItem().toString(); System.out.println(selState); Toast.makeText(getContext(), "Clicked on Planet: " + selState + "", Toast.LENGTH_SHORT).show(); Fragment fragment = new Fragment(); Bundle bundle = new Bundle(); bundle.putString("key", selState); Log.i("BUNDLE", bundle.toString()); fragment.setArguments(bundle); } }); 之间传递数据?

我的适配器:

public  class MyListFragment extends Fragment{

    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

        /*Bundle bundle = this.getArguments();
        String strtext = bundle.getString("key", " ");
        System.out.println(strtext);*/
        System.out.println("prima ancora");

        Bundle arguments = this.getArguments();
        System.out.println("prima");
        if (arguments != null) {
            System.out.println("dopo");

            //String userId = arguments.getString("key");
                //System.out.println("finalmente:"+userId);
             user = getArguments().getString("Key");


        } 

}

我的片段:

{{1}}

1 个答案:

答案 0 :(得分:1)

在开发android之前,请阅读有关Java和面向对象的更多信息。

但您可以使用Interface将数据从适配器传递到片段,通常您可以阅读有关Java - Interface的更多信息

在您的情况下,您可以实现这样的界面:

Public Interface YourInterfaceName{
    void onItemSelected(String key, String Value);
}

在你的片段中你必须实现你的前言:

public class YourFragment extends Fragment implements YourInterface
{
    YourAdapter.setOnItemSelected(this);
}
适配器中的

和finlay执行此操作:

public class Adapter
{
    public void setOnItemSelected(YourInterface yourIntrface)
    {
         this.yourIntrface = yourIntrface;
    }
    .......
    finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
.....
     //instead of creating instance of fragment do this:
     yourInterface.onItemSelected(yourKey, value);     
}