自定义控件(一):组合控件的使用

自定义控件(一):组合控件的使用_第1张图片

一.组合控件的作用

  对于view控件的理解,对于一个控件能够在应用中显示出来.需要java代码的实现,在布局文件中的xml格式的出现简化了布局.但布局文件中的属性,也是需要事先人为指定的.这里需要在values文件下新建一个attrs的xml文件指定布局文件的属性.由于attrs文件指定多个控件,也需要新建一个layout布局文件分别对每一个控件的属性进行控制.组合控件可以实现在xml文件中输入值,达到控制布局的作用.

1.values目录下attrs xml文件指定组合控件的控件属性..



    
    
        
        
        
        
        
        
            
            
            
        

    

2.设置组合控件的布局





    
    
    

3.新建一个自定义组合控件的类,名字与attrs文件名字一样

public class SettingItemView extends RelativeLayout {
    private static final String TAG = "SettingItemView";
    private ImageView mToggle;

    public SettingItemView(Context context) {
        this(context,null);
    }

    public SettingItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //加载自定义数据的布局
        View root =View.inflate(context,R.layout.view_settings_item,this);
        //拿到布局文件中的每一个自定义属性的值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView);

        //拿到每一个自定义属性的值
        String title = typedArray.getString(R.styleable.SettingItemView_sivText);//标题
        boolean flag = typedArray
                .getBoolean(R.styleable.SettingItemView_sivToggle, false);//是否显示开关
        int id = typedArray.getInt(R.styleable.SettingItemView_sivBG, 0);

        //拿到布局中的每一个控件,并赋值
        //标题赋值
        TextView textView= (TextView) findViewById(R.id.view_settings_item_tv_title);
        textView.setText(title);
        //开关是否显示
        mToggle = (ImageView) findViewById(R.id.view_settings_item_iv_toggle);
        mToggle.setVisibility(flag ? View.VISIBLE :View.GONE);
        //整个控件的背景图片的设置
        switch (id) {
            case 0:
                setBackgroundResource(R.drawable.setting_item_bg_top);
                 break;
            case 1:
                setBackgroundResource(R.drawable.setting_item_bg_middle);
                 break;
            case 2:
                setBackgroundResource(R.drawable.setting_item_bg_bottom);
                 break;
        }
        //回收资源
        typedArray.recycle();
    }
    /*
    * 对外提供一个方法,用于控制开关的状态
    * */
    private boolean isOpen=false;
    public  void  setToggle(){
        isOpen=true;
        mToggle.setBackgroundResource(isOpen ?R.drawable.on :R.drawable.off);

    }

}

4.主页面的布局




    
    
    


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