onItemClick - 意图构造函数

时间:2015-07-29 13:20:24

标签: android listview android-intent

编写这部分代码时,我遇到了错误:

ListView lv = (ListView) this.findViewById(R.id.toDoListView);
    lv.setAdapter(tdla);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newIntent = new Intent(this, DisplayMessageActivity.class);//<--- Cannot resolve constructor
            newIntent.putExtra(EXTRA_MESSAGE, "TETTE");
            startActivity(newIntent);
        }
    });

我认为Intent构造函数应该与在一个链接到Button的简单函数中声明它一样:

public void sendMessage(View view){
    Intent newIntent = new Intent(this, DisplayMessageActivity.class);//<--- OK
    ...sth...
    startActivity(newIntent);
}

同样How to handle the click event in Listview in android?显示了一个类似的例子,但我无法弄清楚我错过了什么。

4 个答案:

答案 0 :(得分:3)

更改

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent newIntent = new Intent(this, DisplayMessageActivity.class);//<--- Cannot resolve constructor

    }
});

to for activity

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent newIntent = new Intent(getApplicationContext(), DisplayMessageActivity.class);
    }
});

和片段

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent newIntent = new Intent(getActivity(), DisplayMessageActivity.class);
    }
});

答案 1 :(得分:1)

替换“this”

IS_LAUNCH_MY_PROGRAM_PLEASE

或片段

Intent newIntent = new Intent(yourActivity.this, DisplayMessageActivity.class);

答案 2 :(得分:1)

改变你的意图:

Intent newIntent = new Intent(this, DisplayMessageActivity.class);

到此:

Intent newIntent = new Intent(YourActivity.this, DisplayMessageActivity.class);

在任何点击侦听器中使用intent时,请勿使用“this”关键字。

答案 3 :(得分:1)

您位于Itemclick侦听器内,该侦听器没有上下文(无活动)。

Intent newIntent = new Intent(YourActivity.this, DisplayMessageActivity.class)