android listview 单选按钮点击事件,android listview中实现单选

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" />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值