java无法选择ListView项
我有一个使用自定义适配器的ListView。ListView中的每个元素都包含一个RadioButton和一个TextView
这是我的适配器,它接受员工的ArrayList(当前仅包含名称的对象):
public class EmployeeAdapter extends ArrayAdapter<Employee> {
private ArrayList<Employee> listEmployees;
// Give the adapter the context and layout we are operating it, as well as a list of employees to put in the list.
public EmployeeAdapter(Context context, int layout, ArrayList<Employee> listEmployees) {
super(context, layout, listEmployees);
this.listEmployees = listEmployees;
}
// We override the basic getView function since our list is custom.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// If there is nothing left to put in the view, inflate the view in the rowemployee layout.
if (v == null){
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.rowemployees, null);
}
Employee i = listEmployees.get(position);
// Check if there's still an employee in the list.
if (i != null){
TextView name = (TextView) v.findViewById(R.id.text_employeename);
name.setText(i.getName());
}
// Alternate row colors.
if (position % 2 == 0) {
v.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else {
v.setBackgroundColor(Color.parseColor("#e5fff4"));
}
return v;
}
}
以下是我的XML布局中的listview声明:
<ListView 安卓:id="@+id/employees_list"
安卓:layout_width="fill_parent"
安卓:layout_height="fill_parent"
安卓:paddingLeft="2dp"
安卓:paddingRight="1dp"
安卓:background="@drawable/borderlist"
安卓:choiceMode="singleChoice"
安卓:listSelector="#48ad82"
安卓:layout_below="@id/employees_header">
</ListView>
下面是ListView中每个项目的布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
安卓:id="@+id/row_employee"
安卓:layout_width="fill_parent"
安卓:layout_height="wrap_content"
安卓:paddingLeft="10dp"
安卓:paddingTop="13dp"
安卓:paddingBottom="13dp"
安卓:descendantFocusability="blocksDescendants">
<RadioButton 安卓:id="@+id/radio_employee"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignParentLeft="true"
安卓:focusable="false"/>
<TextView
安卓:id="@+id/text_employeename"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:textSize="18sp"
安卓:layout_toRightOf="@id/radio_employee"
安卓:layout_marginTop="3dp"
安卓:layout_marginLeft="5dp"
安卓:focusable="false" />
</RelativeLayout>
我将一组Employee对象输入ArrayList,并将其推送到适配器,然后在列表上设置一个setOnItemClickListener。侦听器包含以下代码:
OnItemClickListener onItemClickListener_employee
= new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Toast.makeText(getApplicationContext(), String.valueOf(view.isSelected()) , Toast.LENGTH_SHORT).show();
}
};
视图。isSelected()始终返回false。为什么?几个小时以来,我一直在试图找出如何在包含文本视图以外的内容的列表中选择元素,而SDK文档并没有太大帮助,这已经过时了
当我按下列表中的项目时,似乎是文本视图或单选按钮被按下了。focusable=“false”是否应该阻止此(Android custom ListView unable to click on items)
# 1 楼答案
要选择项目,请将以下方法添加到适配器(未测试的代码):
然后在处理程序中,将位置传递给上面的新适配器方法
因为视图只是用于显示数据,所以您实际上并不关心视图本身(除非您想要删除它、点亮它等等)