从gridview接口片段onItemClickListener中的nullpointerexception

时间:2013-05-29 23:22:36

标签: android onitemclicklistener

我正在使用Fragments。我需要扩展FragmentActivity的类来实现从我的片段作为监听器的接口。当我从gridview中单击某个项时,它会触发onItemClick方法,但是即使我在GamePlayActivity中设置了侦听器变量,它也是null。

我的理解是,当我实例化我的片段以设置监听器以及在我的片段类上调用onCreateView()时,我正在处理两件不同的事情。

来自Google的示例使用onClick执行相同的实现,它可以正常运行。不是我的。

例如,

MainActivity extending FragmentActivityFragment class

片段1

public class FragmentOne extends Fragment implements OnItemClickListener {

    Listener listener = null;

    interface Listener {
        public void applyGameLogic();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_fragpane, container, false);
        GridView gridView = (GridView) layout.findViewById(R.id.grid);
        gridView.setAdapter(new ImageAdapter(layout.getContext()));

        gridView.setOnItemClickListener(this);

        return layout;
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        //listener.applyGameLogic(); this listener is null
    }
}

GamePlayActivity

public class GamePlayActivity extends FragmentActivity implements WordPane.Listener, ChainPane.Listener {

    private FragmentOne fragment1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.game_container);

        fragment1 = new FragmentOne();

        fragment1.setListener(this);
    }

    ... applyGameLogic method follows but its empty for now
}

1 个答案:

答案 0 :(得分:1)

fragment1 = new FragmentOne();
fragment1.setListener(this);

您正在创建FragmentOne的新实例,然后将Click侦听器分配给该新实例。相反,您应该在布局中找到现有的片段

FragmentManager fm = getSupportFragmentManager(); // or getFragmentManager() if you aren't using the support library
fragment1 = (FragmentOne)fm.findFragmentById(R.id.fragment_one);

然后设置你的监听器

fragment1.setListener(this);