标签:
变量如下所示:
/** * 原始每行最多显示的个数 */ private static final int INITIAL_MAX_COUNT = 3; private Context mContext; /** * CheckBox 列表 */ private List<CheckBox> mCheckBoxs; /** * 每一个CheckBox 显示的内容 */ private List<String> mSelectedBoxContents;
控件继承自LinearLayout,构造函数中默认设置为水平排列:
public CustomCheckBox(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.mContext = context; this.setOrientation(VERTICAL); mCheckBoxs = new ArrayList<CheckBox>(); mSelectedBoxContents = new ArrayList<String>(); }
初始化每一个CheckBox:
private void initCheckBox(LinearLayout linearLayout, String checkBoxText, int index) { CheckBox checkBox = new CheckBox(mContext); checkBox.setText(checkBoxText); checkBox.setTextSize(15.0f); checkBox.setTextColor(Color.parseColor("#88000000")); checkBox.setOnCheckedChangeListener(listener); checkBox.setTag(index); mCheckBoxs.add(checkBox); LinearLayout.LayoutParams checkBoxParams = new LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); checkBoxParams.gravity = Gravity.CENTER_VERTICAL; checkBoxParams.weight = 1.0f; linearLayout.addView(checkBox, checkBoxParams); }
根据显示的内容,动态生成每一个CheckBox,每行显示3个,超过一行的话每行再另外生成一个LinearLayout,再在每个LinearLayout里面填充CheckBox:
public void setCheckBoxs(List<String> checkBoxContents) { if (checkBoxContents == null || !mCheckBoxs.isEmpty()) return; int checkBoxCount = checkBoxContents.size(); if (checkBoxCount > INITIAL_MAX_COUNT) { initOrientation(LinearLayout.VERTICAL); } else { initOrientation(LinearLayout.HORIZONTAL); } if (this.getOrientation() == LinearLayout.VERTICAL) {// 竖直显示 int checkBoxLines = checkBoxCount % INITIAL_MAX_COUNT == 0 ? checkBoxCount / INITIAL_MAX_COUNT : checkBoxCount / INITIAL_MAX_COUNT + 1; for (int i = 0; i < checkBoxLines; i++) { LinearLayout linearLayout = new LinearLayout(mContext); linearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams lyParams = new LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); /** 最后一行显示余下的个数,其余每行显示最大的显示数目 */ int count = (i == (checkBoxLines - 1) ? checkBoxCount % INITIAL_MAX_COUNT : INITIAL_MAX_COUNT); for (int j = 0; j < count; j++) { String checkBoxText = checkBoxContents.get(i * INITIAL_MAX_COUNT + j); initCheckBox(linearLayout, checkBoxText, i * INITIAL_MAX_COUNT + j); } this.addView(linearLayout, lyParams); } } else {// 水平显示 for (int i = 0; i < checkBoxCount; i++) { String checkBoxText = checkBoxContents.get(i); initCheckBox(this, checkBoxText, i); } } }
贴码工作终于完成,其实只要有思路,代码还是蛮简单的。另外也可以用 RelativeLayout 来实现,具体就不再做撰述。希望对小伙伴们有用。
完整代码地址:http://www.oschina.net/code/snippet_1460984_49512
标签:
原文地址:http://my.oschina.net/u/1460984/blog/479399