我知道这个问题是4年前提出的,但没有一个答案对我有帮助。我正在一本书(Apress的Android Pro 5)中试图让这个项目发挥作用。但是,强制性书籍已经过时。
我有一个简单的ListView,底部有一个按钮。每个列表视图项旁边都有一个复选框。单击按钮时,应该说" ListView在位置"。
处被检查一切都在视觉上很好地加载。但是,当我按照书中的说明操作时,按钮什么都不做。当我按照Get listview item position on button click文章中的任何说明操作时,单击按钮时应用程序会崩溃。请注意,我的代码是我的全部内容。没有任何其他方法或其他任何方法。这是我的代码:
//设置代码的主要部分
public class MainActivity extends AppCompatActivity {
private ListView listView1;
private Button button1;
private ArrayAdapter<String> listAdapter1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1 = (ListView) findViewById(R.id.listView1);
String[] someColors = new String[]{"Red", "Orange", "Yellow", "Green",
"Blue", "Indigo", "Violet", "Black", "White"};
ArrayList<String> colorArrayList = new ArrayList<String>();
colorArrayList.addAll(Arrays.asList(someColors));
listAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, colorArrayList);
listView1.setAdapter(listAdapter1);
//添加复选框
listView1.setChoiceMode(listView1.CHOICE_MODE_MULTIPLE);
//这是列表视图的onItemClickListener
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String itemValue = (String)
listView1.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), itemValue,
Toast.LENGTH_LONG).show();
}
});
}
//这是根本没有响应的动作。它确实在运行时不会发生任何事情。
public void doClick(View view) {
int count = listView1.getCount();
SparseBooleanArray viewItems = listView1.getCheckedItemPositions();
for (int i = 0; i < count; i++) {
if(viewItems.get(i)){
String selectColor = (String)listView1.getItemAtPosition(i);
Log.v("List View", selectColor + "is checked at position" + i);
}
}
}
好的方面,这是我的XML:
<LinearLayout
android:layout_width="368dp"
android:layout_height="492dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="62dp"
android:text="@string/sub"
android:onClick="doClick"
/>
</LinearLayout>
答案 0 :(得分:0)
从
更改以下行@Override
public void onItemClick (AdapterView < ? > parent, View view, int
position,long id){
String itemValue = (String)
listView1.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), itemValue,
Toast.LENGTH_LONG).show();
}
});
要
@Override
public void onItemClick (AdapterView < ? > parent, View view, int
position,long id){
String itemValue = colorArrayList.get(position);
Toast.makeText(getApplicationContext(), itemValue,
Toast.LENGTH_LONG).show();
}
});