ListView OnItemClick侦听器不起作用?

时间:2016-03-07 10:13:26

标签: android listview android-fragments

我试图在列表视图OnItemClick监听器上调用片段中的片段,但是点击监听器对我不起作用。 我已使用适配器设置了列表项。

这是我的代码:

public class ProductListFragment extends Fragment {

    FragmentManager mFragmentManager;
    ListView listView;

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

        View view = inflater.inflate(R.layout.product_list, container, false);
        listView = (ListView) view.findViewById(R.id.listView);
        listView.setAdapter(new ProductListAdapter(getActivity()));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new ProductFragment()).commit();

            }
        });

    return view;

     }
}

2 个答案:

答案 0 :(得分:0)

请使用此代码替换fragment-

img src html tag

修改

请将Fragment类的视图设置为 -

 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
 fragmentTransaction.replace(R.id.containerView, new ProductFragment());
 fragmentTransaction.commit();

答案 1 :(得分:0)

您尚未初始化FragmentManager

public class ProductListFragment extends Fragment {

    FragmentManager mFragmentManager;
    ListView listView;

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

        View view = inflater.inflate(R.layout.product_list, container, false);
        listView = (ListView) view.findViewById(R.id.listView);
        listView.setAdapter(new ProductListAdapter(getActivity()));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                /** initialize fragment manager */
                mFragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new ProductFragment()).commit();

            }
        });

        return view;
    }
}