5 android
我使用adapter = new SimpleCursorAdapter(这个,android.R.layout.simple_list_item_multiple_choice,cur,cols,views)来创建一个多选控件,但我不满足于多选控件中textview的样式,所以我必须使用以下代码来创建多选控件的新布局.它运作良好,但我认为这不是一个好方法,有没有好的代码?谢谢!
adapter = new SimpleCursorAdapter(this,R.layout.mysimple_list_item_multiple_choice,cur,cols,views);
lv.setAdapter(adapter);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Run Code Online (Sandbox Code Playgroud)
mysimple_list_item_multiple_choice.xml
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceMedium"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:ellipsize="end"
android:singleLine="true"
/>
Run Code Online (Sandbox Code Playgroud)
您需要扩展BaseAdapter来创建自定义适配器。通过自定义适配器,列表视图的每一行都使用 xml 布局,因此您可以为行创建自定义布局。
自定义适配器的示例代码:
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] StrValues;
public ImageAdapter(Context context, String[] StrValues) {
this.context = context;
this.StrValues = StrValues;
}
// getView that displays the data at the specified position in the data set.
public View getView(int position, View convertView, ViewGroup parent) {
// create a new LayoutInflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
view = null;
convertView = null;// avoids recycling of list view
if (convertView == null) {
view = new View(context);
// inflating grid view item
view = inflater.inflate(R.layout.list_view_item, null);
// set value into textview
TextView textView = (TextView) view
.findViewById(R.id.list_item_label);
textView.setText(StrValues[position]);
}
return view;
}
// Total number of items contained within the adapter
@Override
public int getCount() {
return StrValues.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
设置适配器:
listView = (ListView) findViewById(R.id.listView1);
// setting adapter on listview
listView.setAdapter(new ImageAdapter(this, StrValues));
Run Code Online (Sandbox Code Playgroud)
示例链接:
R.layout.list_view_item 是列表视图的自定义 xml,您可以在其中添加所需的视图。