android - 如何将数据从 Adapter 传递到 Fragment?

标签 android android-fragments android-adapter

如何在adapterfragment之间传递数据?

我的适配器:

finalHolder.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);
    }
});

我的 fragment :

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");


        } 

}

最佳答案

您可以使用接口(interface)将数据从适配器传递到 fragment ,通常,您可以在这里找到它:Java - Interface

在您的情况下,您可以实现如下接口(interface):

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

在你的 fragment 中你必须实现你的接口(interface):

public class YourFragment extends Fragment implements YourInterface
{
    YourAdapter.setOnItemSelected(this);
}

并在您的适配器中执行此操作:

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);     
}

关于android - 如何将数据从 Adapter 传递到 Fragment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38591574/

相关文章:

android - 图表引擎独立移动图例

Android Viewpager如何动态移除一个Fragment?

android - 在数据 fragment 之间传递数据

android - FragmentPagerAdapter 未正确删除项目( fragment )

android - ProgressDialog 中的进度单元

android - TableRow 高度不会根据 android TableLayout 中的内容增加吗?

android - 蓝牙低功耗 (BLE) 设备与华为手机的连接问题

Android ListView 每次滚动都会滞后,即使使用 ViewHolder

java - 如何解决 "The content of the adapter has changed but ListView did not receive a notification”异常

android - RecyclerView android中的Admob原生广告