Fragments和ListFragment之间的通信

时间:2015-08-13 15:44:41

标签: android android-fragments android-activity fragment

我在一个活动中有两个片段,我的第一个片段是扩展ListFragment类,并且在其xml布局中有一个ListView小部件,其id为'list'。我为这个List编写了一个自定义适配器并且工作正常但是我需要单击一个项来将一些值传递给另一个片段。对于itemClick事件,我想,我必须使用ListFragment类的onListItemClick()方法。但是当我运行应用程序并单击列表中的项目时,没有任何事情发生。

public class List extends ListFragment {

    private Context context;
    ListAdapter listAdapter;
    OnHeadlineSelectedListener mCallback;

    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }


    @Override
    public void onCreate (Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        KnlContainer knlModel = new KnlContainer();
        listAdapter = new ListAdapter((Activity)context,knlModel);

    }

    @Override
    public void onAttach(Activity activity){

        super.onAttach(activity);
        context = activity;

      //I need to call this instance of interface to comminacation with Activity
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }

    }
    @Override
     public void onListItemClick(ListView l, View v, int position, long id) {

      // Send the event to the host activity

       //for comminacation with activity

        mCallback.onArticleSelected(position);
            Log.e("STAT","OK");
        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        LinearLayout rootView = (LinearLayout)inflater.inflate(R.layout.knl_list_fragment, null);

        ListView knllrList = (ListView)rootView.findViewById(android.R.id.list);
        knllrList.setAdapter(listAdapter);


        return rootView;

    }
}

我必须在适配器中定义clicklistener吗?

2 个答案:

答案 0 :(得分:0)

适配器纯粹用于处理数据并为列表视图中的每一行生成视图。

根据Android ListFragment API,您必须使用 ListFragment.setListAdapter()

左右....

 @Override
 public void onCreate (Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    KnlContainer knlModel = new KnlContainer();

    setListAdapter(new ListAdapter((Activity)context, knlModel));
 }

答案 1 :(得分:0)

如果您的列表包含其他可点击元素,例如复选框,则您必须在focusable之前将其false属性设置为onListItemClick将工作。

请参阅此答案:ListFragment OnListItemClick not being called

如果这不起作用,另一个可能的解决方案是确保ListView的ID定义为android:id="android:id/list" {{ 1}}。