无法在项目单击侦听器上获取gridView

时间:2012-04-12 09:23:26

标签: android gridview fragment onitemclicklistener

我无法在Fragment中获得gridView的setOnItemClickListener。可能是什么问题?

这是我的代码::

 public class MainMenuFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.main_menu_fragment, container, false);

        itemsGridViewObj = (GridView) view.findViewById(R.id.itemsGridView);



        itemsGridViewObj.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {

                Log.d(TAG, "--> onItemClick listener...");      // Can not getting this method.
                /*if(position == 1) {
                    FruitMenuFragment fruitMenuFragment = new FruitMenuFragment();
                    fragmentTransaction.replace(android.R.id.content, fruitMenuFragment);
                    fragmentTransaction.commit();
                }*/
            }
        });

        return view;
    }
}`

2 个答案:

答案 0 :(得分:9)

您可能需要在ButtonView中设置以下内容。     机器人:可聚焦=“假”     机器人:focusableInTouchMode = “假”

请参阅adding CheckBox to list row loses my onItemClick events?

答案 1 :(得分:3)

使用Fragments时,视图的初始化发生在两个阶段。

视图仅在onCreateView方法之后被充气(因此可访问)。此方法仅用于对视图进行膨胀并将其返回到Fragment。

因此,任何查找视图和设置onClickListener的逻辑都应该在onActivityCreated()函数中完成,因为这是您可以访问膨胀视图的第一个点。

查看http://developer.android.com/reference/android/app/Fragment.html#Lifecycle

上的Google文档

以下是您调整的代码,以符合我上面所描述的内容:

public class MainMenuFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment

    return inflater.inflate(R.layout.main_menu_fragment, container, false);     
}

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

    GridView itemsGridViewObj = (GridView) findViewById(R.id.itemsGridView);

    itemsGridViewObj.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {

        Log.d(TAG, "--> onItemClick listener..."); // You should see this now
        /*if(position == 1) {
            FruitMenuFragment fruitMenuFragment = new FruitMenuFragment();
            fragmentTransaction.replace(android.R.id.content, fruitMenuFragment);
            fragmentTransaction.commit();
        }*/
    }});
}
}