item.xml
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* 实现listview中的单选
*/
public class CheckableLinearLayout extends RelativeLayout implements Checkable {
private boolean mChecked;
private TextView textView;
private ImageView imageView;
private Context mContext;
public CheckableLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
textView = new TextView(context);
textView.setTextSize(18);
textView.setTextColor(mContext.getResources().getColor(android.R.color.black));
imageView = new ImageView(context);
//设置文字
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textView.setPadding(dip2px(mContext, 10), dip2px(mContext, 10), dip2px(mContext, 10), dip2px(mContext, 10));
addView(textView, layoutParams);
//设置图片
RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.CENTER_IN_PARENT);
imageView.setPadding(dip2px(mContext, 10), dip2px(mContext, 10), dip2px(mContext, 10), dip2px(mContext, 10));
imageView.setScaleType(ImageView.ScaleType.CENTER);
addView(imageView, layoutParams1);
}
@Override
public void setChecked(boolean checked) {
mChecked = checked;
setBackgroundDrawable(checked ? new ColorDrawable(0xffe4e4e4) : null);
if (checked) {
imageView.setVisibility(VISIBLE);
imageView.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ico_check));
} else {
imageView.setVisibility(GONE);
}
}
public void setTitle(String title) {
textView.setText(title);
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void toggle() {
setChecked(!mChecked);
}
//*setPadding,并没有提供设置dp的方法,如果需要设置dp的话,就要将dp转换成px了
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
android:id="@+id/school_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
list.xml
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="@color/divide"
android:dividerHeight="1px" />