你要做的是用你自己的row_layout.xml文件创建一个自定义ListView,一个CustomListViewObject有一个boolean来检查元素是否被点击,最后,一个@987654325 @ 检查是否选择了行元素。
你的行布局row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="12dp"
android:text="Large Text"
android:id="@+id/textfield"/>
</LinearLayout>
这就是你的行类应该是这样的:
public class CustomRowClass {
private String input;
private boolean selected;
public BallotEntryClass() {
}
public BallotEntryClass(String input, boolean selected) {
this.input = input;
this.selected = selected;
}
//setters and getters here
}
最后,你的适配器:
public class CustomListViewAdapter extends BaseAdapter {
private ArrayList<CustomRowClass> listData;
private LayoutInflater layoutInflater;
private Context context;
public CustomListViewAdapterBallot(Context context, ArrayList<CustomRowClass> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
this.context = context;
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.row_layout, null);
holder = new ViewHolder();
holder.input = (TextView) convertView.findViewById(R.id.textfield);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.textfield.setText(listData.get(position).getInput());
//check here if state = 1 which means selected state
if(listData.get(position).isSelected()){
convertView.setBackgroundColor(Color.GREEN);
}
else{
convertView.setBackgroundColor(Color.WHITE);
}
return convertView;
}
static class ViewHolder {
TextView input;
}
}
就是这样。要使用它,请这样做:
ListView sampleListView = (ListView) findViewById(R.id.listView);
//create your listView with your custom object
ArrayList<CustomRowClass> data = new ArrayList<>();
for(int i = 0 ; i < 10 ; i ++){
CustomRowClass entry = new CustomRowClass("Name " + i, false);
data.add(entry);
}
//create your adapter, use the nameAndAgeList ArrayList
CustomListViewAdapter customAdapter = new CustomListViewAdapter(this, data);
//get your listView and use your adapter
listView.setAdapter(sampleListView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomRowClass selection = (CustomRowClass) listView.getItemAtPosition(position);
selection.setSelected(true);
adapter.notifyDataSetChanged();
}
});