TextView两图片实现点击切换开关效果:
//xml
<TextView
android:id="@+id/iv_reason"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/corner_border_feedback_n"
android:gravity="center"
android:text="推送時間造成困擾" />
initSwitcher(iv_reason, "on"); //初始
String value = (iv_reason.getTag() != null) && ((String) iv_reason.getTag()).equals("off") ? "2" : "1"; //取值
/**
* 單選開關
*
* @param tv
* @param tag
*/
private void initSwitcher(final TextView tv, String tag) {
//config
final String[] tags = {"on", "off"};
final int[] colors = {0xfff77518, 0xff999999};
final int[] resIds = {R.drawable.corner_border_feedback_p, R.drawable.corner_border_feedback_n};
tag = tag.equals(tags[0]) ? tags[0] : tags[1]; // check data
int resId = tag.equals(tags[0]) ? resIds[0] : resIds[1];
int color = tag.equals(tags[0]) ? colors[0] : colors[1];
tv.setBackgroundResource(resId);
tv.setTextColor(color);
tv.setTag(tag);
tv.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
String tagto = (view.getTag() != null) && ((String) view.getTag()).equals(tags[1]) ? tags[0] : tags[1];
if (tagto.equals(tags[0])) {
tv.setBackgroundResource(resIds[0]);
tv.setTextColor(colors[0]);
//TODO:互斥
} else {
tv.setBackgroundResource(resIds[1]);
tv.setTextColor(colors[1]);
}
tv.setTag(tagto);
}
});
}
ImageView、Button两图片实现点击切换开关效果:
//xml
<ImageView
android:id="@+id/iv_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:contentDescription="@null"
android:scaleType="fitXY"
android:src="@drawable/ic_feedback_submit_n"/>
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@drawable/ic_feedback_submit_n"
android:gravity="center"/>
// ImageView
final String[] tags = {"on", "off"};
final ImageView iv_send = (ImageView) v.findViewById(R.id.iv_send);
iv_send.setTag(tags[0]); //init
iv_send.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
String tagto = (view.getTag() != null) && ((String) view.getTag()).equals(tags[1]) ? tags[0] : tags[1];
iv_send.setImageResource(tagto.equals(tags[0]) ? R.drawable.ic_feedback_submit_n: R.drawable.ic_feedback_submit_p);
iv_send.setTag(tagto);
}
});
// Button
final Button btn_send = (Button) v.findViewById(R.id.btn_send);
btn_send.setTag(tags[0]); //init
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
String tagto = (view.getTag() != null) && ((String) view.getTag()).equals(tags[1]) ? tags[0] : tags[1];
btn_send.setBackgroundResource(tagto.equals(tags[0]) ? R.drawable.ic_feedback_submit_n: R.drawable.ic_feedback_submit_p);
btn_send.setTag(tagto);
}
});