这期内容当中小编将会给大家带来有关怎么在Android中通过自定义View实现任意布局,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
RelativeRadioGroup
public class RelativeRadioGroup extends RelativeLayout implements CompoundButton.OnCheckedChangeListener {
private int checkId = -1;
private CompoundButton.OnCheckedChangeListener mChildOnCheckedChangeListener;
public RelativeRadioGroup(Context context) {
super(context);
}
public RelativeRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RelativeRadioGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
//添加监听
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
if (v instanceof RadioButton && !(v instanceof CompoundButton.OnCheckedChangeListener)) {
((RadioButton) v).setOnCheckedChangeListener(this);
}
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setCheck(buttonView.getId(), isChecked);
}
public void check(@IdRes int checkId) {
if (checkId == -1 || this.checkId == checkId) {
return;
}
setCheck(checkId, true);
}
public void clearCheck() {
setCheck(-1, false);
}
public int getCheckedRadioButtonId() {
return this.checkId;
}
/**
* 设置选中状态
*/
private void setCheck(@IdRes int checkId, boolean isChecked) {
if (checkId != -1 && this.checkId == checkId) {
return;
}
if (checkId != -1) {
CompoundButton view = (CompoundButton) findViewById(checkId);
//未选中的RadioButton被选中
if (checkId != this.checkId && isChecked) {
this.checkId = checkId;
if (mChildOnCheckedChangeListener != null) {
mChildOnCheckedChangeListener.onCheckedChanged(view, true);
}
//某个RadioButton被选中,将其他的改为未选中
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
if (v instanceof RadioButton && v.getId() != checkId) {
((RadioButton) v).setChecked(false);
} else if (v instanceof RadioButton && v.getId() == checkId) {
((RadioButton) v).setChecked(true);
}
}
}
//被选中的RadioButton被取消选中
if (checkId == this.checkId && !isChecked) {
this.checkId = checkId;
if (mChildOnCheckedChangeListener != null) {
mChildOnCheckedChangeListener.onCheckedChanged(view, false);
}
}
} else {
//清空所有选择
if (this.checkId != -1) {
this.checkId = -1;
CompoundButton view = (CompoundButton) findViewById(this.checkId);
//将选中的置为未选中
if (view instanceof RadioButton) {
view.setChecked(false);
}
}
}
}
public void setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener mChildOnCheckedChangeListener) {
this.mChildOnCheckedChangeListener = mChildOnCheckedChangeListener;
}
}
Android是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。
上述就是小编为大家分享的怎么在Android中通过自定义View实现任意布局了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。