簡體   English   中英

如何將數據從適配器傳遞到片段?

[英]How can pass data from Adapter to Fragment?

如何在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);
    }
});

我的片段:

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


        } 

}

您可以使用接口將數據從適配器傳遞到片段,通常,您可以在這里找到它: Java - 接口

在您的情況下,您可以實現這樣的接口:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM