Android中自定义组合控件

1.自定义属性resource资源

    

        


        
        

        
        
            
            
            
        

        
        
    
2.自定义View
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SettingItemView extends RelativeLayout {
	// 枚举
	// 
	// 
	// 

	private static final int	BACKGROUND_START	= 0;
	private static final int	BACKGROUND_MIDDLE	= 1;
	private static final int	BACKGROUND_END		= 2;

	private TextView			mTvTitle;
	private ImageView			mIvToggle;

	private boolean				isOpened			= true;	// 用来记录是否是打开的

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

	public SettingItemView(Context context, AttributeSet attrs) {
		super(context, attrs);

		// 挂载xml布局
		View.inflate(context, R.layout.view_setting_item, this);

		// 初始化view
		mTvTitle = (TextView) findViewById(R.id.view_tv_title);
		mIvToggle = (ImageView) findViewById(R.id.view_iv_toggle);

		// 读取属性值
		TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView);

		String title = ta.getString(R.styleable.SettingItemView_sivTitle);
		int background = ta.getInt(R.styleable.SettingItemView_sivBackground, BACKGROUND_START);
		boolean toggle = ta.getBoolean(R.styleable.SettingItemView_sivToggle, true);

		ta.recycle();

		// 设置title
		mTvTitle.setText(title);
		// 设置背景
		switch (background) {
		case BACKGROUND_START:
			setBackgroundResource(R.drawable.setting_start_selector);
			break;
		case BACKGROUND_MIDDLE:
			setBackgroundResource(R.drawable.setting_middle_selector);
			break;
		case BACKGROUND_END:
			setBackgroundResource(R.drawable.setting_end_selector);
			break;
		default:
			setBackgroundResource(R.drawable.first_normal);
			break;
		}
		// 设置开关显示
		mIvToggle.setVisibility(toggle ? View.VISIBLE : View.GONE);
	}

	public void toggle() {
		// 如果开关是打开的,就关闭,如果是关闭的就打开
		isOpened = !isOpened;
		mIvToggle.setImageResource(isOpened ? R.drawable.on : R.drawable.off);
	}

	public boolean isToggleOpened() {
		return isOpened;
	}

	/**
	 * 设置开关是否打开
	 * 
	 * @param isOpened
	 */
	public void setToggleOpened(boolean isOpened) {
		this.isOpened = isOpened;
		mIvToggle.setImageResource(isOpened ? R.drawable.on : R.drawable.off);
	}

}
3.布局文件




    

    

4.自定义view的使用



    

    

    

    

4.效果图

Android中自定义组合控件_第1张图片



你可能感兴趣的:(Android基础总结)