public void onListItemClick(ListView listview,View itemView,int position,long id) {
ListView lv=(ListView)findViewById(R.id.drinks_lv);
Intent intent = new Intent(DrinkCategoryActivity.this, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_DRINKNO,(int)id);
startActivity(intent);
}
DetailActivity.java
public class DetailActivity extends AppCompatActivity {
public static final String EXTRA_DRINKNO = "drinkNo";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
int drinkNo = (int) getIntent().getExtras().get(EXTRA_DRINKNO);
Drink drink = Drink.drinks[drinkNo];
ImageView photo =(ImageView)findViewById(R.id.photo);
photo.setImageResource(drink.getImageResourceId());
photo.setContentDescription(drink.getName());
TextView name=(TextView)findViewById(R.id.name);
name.setText(drink.getName());
TextView description=(TextView)findViewById(R.id.description);
description.setText(drink.getDescription());
}
}
代码的第一部分是从Head First Android Development-2015提取的DrinkCategoryActivity类,它应该导航到DetailActivity类,但是什么也没有发生。listview在单击饮料的list选项时不执行任何操作,它没有显示任何错误,但是第三部分activity(DetailActivity未启动,应显示图像,名称和描述。
最佳答案
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener
{
final String numbers = {"1","2","3"};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.riga, numbers);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adattatore, final View componente, int position, long id )
{
Toast.makeText(getApplicationContext(), numbers[position], Toast.LENGTH_LONG).show();
}
}
里加布局
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:id="@+id/textView"
android:textSize="36sp" />
Activity_main布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView" />
</LinearLayout>
这是我的旧应用,用于接管使用AdapterView.OnItemClickListener的按键数量