自定义控件-组合法



 → 在布局中使用自定义的组合控件(本例不带自有命名空间):
       

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        labelFontSize="16"

        labelPosition="left"

        labelText="@string/hello" />

 

   

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="20dp"

        labelFontSize="26"

        labelPosition="top"

        labelText="兴趣爱好" />

→  令控件继承自ViewGroup的子类:
    public class LabelEditText extends LinearLayout {...}

→ 声明要从布局文件中读入的属性:
    private String labelText;

private int labelFontSize;

private String labelPosition;

→ 在创建实例时逐个读入属性
    public LabelEditText(Context context, AttributeSet attrs) {

super(context, attrs);

 

int resourceId = attrs.getAttributeResourceValue(null, "labelText", 0);

if (resourceId == 0) {

labelText = attrs.getAttributeValue(null, "labelText");

} else {

labelText = getResources().getString(resourceId);

}

if (labelText == null) {

throw new RuntimeException("必须设置labelText属性.");

}

resourceId = attrs.getAttributeResourceValue(null, "labelFontSize", 0);

if (resourceId == 0){

labelFontSize = attrs.getAttributeIntValue(null, "labelFontSize", 14);

}else{

labelFontSize = getResources().getInteger(resourceId);

}

resourceId = attrs.getAttributeResourceValue(null, "labelPosition", 0);

if (resourceId == 0){

labelPosition = attrs.getAttributeValue(null, "labelPosition");

}else{

labelPosition = getResources().getString(resourceId);

}

if (labelPosition == null){

labelPosition = "left";

}
                
                loadLayout(); 



→ 根据读入的属性载入具体布局
    private void loadLayout(){
        String infService = Context.LAYOUT_INFLATER_SERVICE;

LayoutInflater li;

li = (LayoutInflater) context.getSystemService(infService);

LinearLayout linearLayout = null;

if ("left".equals(labelPosition)){

linearLayout = (LinearLayout) li.inflate(R.layout.labeledittext_horizontal, this);

}else if ("top".equals(labelPosition)){

linearLayout = (LinearLayout) li.inflate(R.layout.labeledittext_vertical, this);

}else{

throw new RuntimeException("labelPosition属性的值只能是left或top.");

}

textView = (TextView) findViewById(R.id.textview);

textView.setTextSize(labelFontSize);

textView.setText(labelText);

    } 

效果图:
 自定义控件-组合法_第1张图片

你可能感兴趣的:(Android自定义控件)