我想在用户点击列表时打开更多意图,但每次点击列表项时都会打开相同的活动
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class McLarenActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
//this the arraylist and i want to open further activities when a user clicks on a single arraylist an activity about it opens but currently when i click the 1 and 2 list open the same activity opens up.
final ArrayList<Word> words = new ArrayList<Word>();
words.add(new Word("2017", "720 S", R.drawable.mclaren2017720s));
words.add(new Word("2015", "675lt", R.drawable.mclaren2015675lt));
words.add(new Word("2015", "P1 GTR", R.drawable.mclaren2015p1gtr));
words.add(new Word("2013", "P1", R.drawable.mclaren2013p1));
words.add(new Word("1994", "F1", R.drawable.mclaren1994f1));
WordAdapter adapter = new WordAdapter(this, words);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long 1) {
// the word item clicked
Word word = words.get(0);
Intent i = new Intent(McLarenActivity.this, mclaren720s.class);
startActivity(i);
}
});
//these are the set on clicker i have used but some how they are not working correctly
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// the word item clicked
Word word = words.get(1);
Intent i = new Intent(McLarenActivity.this, mclaren675lt.class);
startActivity(i);
}
});
答案 0 :(得分:0)
您正在设置项目单击侦听器两次。 ListView只能有一个项目单击侦听器。所以基本上第一项单击侦听器被替换为秒并且未被使用。
您应该只设置项目单击侦听器一次,并根据position
(或可能id
)值执行不同的操作。像这样的东西
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Word word = words.get(position); // I don't know why you need `word` variable, it's not used anywhere in your code
if (position == 0) {
Intent i = new Intent(McLarenActivity.this, mclaren720s.class);
startActivity(i);
} else if (position == 1) {
Intent i = new Intent(McLarenActivity.this, mclaren675lt.class);
startActivity(i);
}
});