代码段

自定义View和自定义属性

public class CustomView extends FrameLayout implements OnClickListener {
    private CustomListener customListener = null;
    private Drawable mSrc = null, mBackground = null;
    private String mText = "";
    private int mTextColor = 0;
    private float mTextSize = 20;
    private int mCustomId = 0;
    
    private Button btn;
    private ImageView mBackgroundView = null;
    private ImageButton mButtonView = null;
    private TextView mTextView = null;
    private LayoutParams mParams = null;

    public CustomView(Context context) {
        super(context);
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.custom_view);
        
        mSrc = a.getDrawable(R.styleable.custom_view_src);
        mBackground = a.getDrawable(R.styleable.custom_view_background);
        
        mText = a.getString(R.styleable.custom_view_text);
        mTextColor = a.getColor(R.styleable.custom_view_textColor, Color.WHITE);
        mTextSize = a.getDimension(R.styleable.custom_view_textSize, 20);
        mCustomId = a.getInt(R.styleable.custom_view_custom_id, 0);
        
        mTextView = new TextView(context);
        mTextView.setTextSize(mTextSize);
        mTextView.setTextColor(mTextColor);
        mTextView.setText(mText);
        mTextView.setGravity(Gravity.CENTER);
        mTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        
        mButtonView = new ImageButton(context);
        mButtonView.setImageDrawable(mSrc);
        mButtonView.setBackgroundDrawable(null);
        mButtonView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        mButtonView.setOnClickListener(this);
        
        mBackgroundView = new ImageView(context);
        mBackgroundView.setImageDrawable(mBackground);
        mBackgroundView.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        
        addView(mBackgroundView);
        addView(mButtonView);
        addView(mTextView);
        
        this.setOnClickListener(this);
        a.recycle();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值