上一篇知道可以使用android自带的listview的chiocemode的单选模式实现。但那个布局是系统自带的checkedTextView,有时候我们需要自己实现布局,那么下面我们开始实现
自定义组合布局,实现checkable接口。
public class SingleView extends LinearLayout implements Checkable {
private TextView mText;
private CheckBox mCheckBox;
public SingleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
public SingleView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public SingleView (Context context) {
super(context);
initView(context);
}
private void initView(Context context){
// 填充布局
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.item_single_layout , this, true);
mText = (TextView) v.findViewById(R.id. title);
mCheckBox = (CheckBox) v.findViewById(R.id. checkbox);
}
@Override
public void setChecked( boolean checked) {
mCheckBox.setChecked(checked);
}
@Override
public boolean isChecked() {
return mCheckBox.isChecked();
}
@Override
public void toggle() {
mCheckBox.toggle();
}
public void setTitle(String text){
mText.setText(text);
}
}
activity中试下代码:
public class MainActivity extends Activity {
private ArrayList<String> groups;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
listView = (ListView) findViewById(R.id. listView);
groups = new ArrayList<String>();
groups.add( "11");
groups.add( "22");
groups.add( "33");
groups.add( "44");
groups.add( "55");
groups.add( "66");
groups.add( "77");
groups.add( "88");
groups.add( "99");
groups.add( "00");
SingleAdapter singleAdapter = new SingleAdapter();
listView.setAdapter(singleAdapter);
Button button = (Button) findViewById(R.id. button);
button.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
PickNum();
}
});
}
private void PickNum() {
int position = listView.getCheckedItemPosition();
if (ListView. INVALID_POSITION != position) {
Toast. makeText(MainActivity.this, groups.get(position), 0).show();
}
}
private class SingleAdapter extends BaseAdapter {
@Override
public int getCount() {
return groups.size();
}
@Override
public Object getItem( int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId( int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView( final int position, View convertView,
ViewGroup parent) {
final SingleView singleView = new SingleView(MainActivity.this );
singleView.setTitle( groups.get(position));
return singleView;
}
}
}
效果:
如果要替换默认checkbox的图标显示,设置checkbox的button属性即可。
附件: