我的android程序中有一个ListView(字符串数组中的一组预定义的引号),当选择一个项目时,它似乎不起作用。 ListView已填充,但我的onClickListener中的toast消息从未被调用。我不确定这里的问题是什么。我以前从未遇到过这个问题。
这是我的onCreate方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
List<String> quotesList = new ArrayList<String>(Arrays.asList(quotes));
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, quotesList);
listView.setAdapter(arrayAdapter);
listView.setOnItemSelectedListener(new ListView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Toast.makeText(getApplicationContext(), "Toast", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
}
这是我的activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#b2cfff"
tools:context="com.examples.myteststuff.listviews.MainActivity">
<LinearLayout
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:src="@drawable/icon"
android:layout_height="wrap_content" />
<ListView
android:layout_width="match_parent"
android:id="@+id/listView"
android:background="@drawable/border"
android:layout_marginHorizontal="8dp"
android:layout_marginVertical="8dp"
android:layout_height="match_parent"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
答案 0 :(得分:1)
请尝试setOnItemClickListener
:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Toast", Toast.LENGTH_SHORT).show();
}
});
希望这有帮助