目前,代码我只在该列表视图的索引0处显示数据(点击时的新活动) - 而不是我实际点击的项目。我想以某种方式更改我的代码,以便它可以显示索引n处的数据(n是我在列表视图中单击的项目):
ResultsActivity.java
final ArrayList<String> searchResults = getValuesFromJSON(jsonResult);
final ListView listView = (ListView) findViewById(R.id.listView);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, searchResults);
listView.setAdapter(arrayAdapter);
//list items become clickable and open the movie detail page which displays the movie data of the specific movie
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newActivity = new Intent(ResultsActivity.this, MoviePage.class);
newActivity.putStringArrayListExtra("movie data", searchResults);
startActivity(newActivity);
}
});
}
MoviePage.java
ArrayList<String> searchResults = getIntent().getStringArrayListExtra("movie data");
TextView t = (TextView)findViewById(R.id.textViewfinal);
t.setText(searchResults.get(9));
答案 0 :(得分:1)
只需在列表视图中设置onclick监听器,即可收听项目点击事件 将其放入活动中的onCreate方法中:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//you can move the textview to a class variable if you want
TextView t = (TextView)findViewById(R.id.textViewfinal);
t.setText(searchResults.get(position));
}
});
更新:您希望将该位置传递给下一个活动,就像将您的searchResults传递给MoviePage一样,只需这样做:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newActivity = new Intent(ResultsActivity.this, MoviePage.class);
newActivity.putStringArrayListExtra("movie data", searchResults);
newActivity.putExtra("position",position);//pass the position to the next activity
startActivity(newActivity);
}
});
现在在MoviePage.java
ArrayList<String> searchResults = getIntent().getStringArrayListExtra("movie data");
int position = getIntent().getIntExtra("position",0);
TextView t = (TextView)findViewById(R.id.textViewfinal);
t.setText(searchResults.get(position));
答案 1 :(得分:1)
试试这个:
<强> ResultsActivity.java 强>
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newActivity = new Intent(ResultsActivity.this, MoviePage.class);
newActivity.putExtra("movie data", searchResults.get(position));
startActivity(newActivity);
}
});
<强> MoviePage.java 强>
Bundle extras = getIntent().getExtras();
if (extras != null) {
TextView t = (TextView)findViewById(R.id.textViewfinal);
t.setText(extras.getString("movie data"));
}