2 taocgz taocgz 于 2016.09.08 11:20 提问

自定义复合控件,这段代码有什么错误,在布局里显示不了。 2C

public class Payment extends RelativeLayout {

private ImageView mImageView;
private TextView mTextView;
private RadioButton mRadioButton;

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

public Payment(Context context, AttributeSet attrs){
    this(context, null, 0);
}

public Payment(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    // TODO Auto-generated constructor stub
    TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.payment);//获取自定义属性和默认值             
    int paymentLogoRes = mTypedArray.getInt(R.styleable.payment_paymentlogores, R.drawable.other);
    int paymentLogoId = mTypedArray.getInt(R.styleable.payment_paymentlogoid, 0);   
    String paymentName = mTypedArray.getString(R.styleable.payment_paymentname);
    int paymentNameId = mTypedArray.getInt(R.styleable.payment_paymentnameid, 0);
    int paymentradiobuttonid = mTypedArray.getInt(R.styleable.payment_paymentradiobuttonid, 0);
    mTypedArray.recycle();

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    mImageView = new ImageView(context);

    lp.addRule(RelativeLayout.CENTER_VERTICAL);
    mImageView.setLayoutParams(lp);
    mImageView.setId(paymentLogoId);
    mImageView.setImageResource(paymentLogoRes);

    mTextView = new TextView(context);
    lp.addRule(RelativeLayout.ALIGN_RIGHT, mImageView.getId());
    lp.setMargins(10, 0, 0, 0);
    mTextView.setLayoutParams(lp);
    mTextView.setId(paymentNameId);
    mTextView.setText(paymentName);

    mRadioButton = new RadioButton(context);
    lp.addRule(RelativeLayout.ALIGN_RIGHT, 0);
    lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
    lp.setMargins(0, 0, 0, 0);
    mRadioButton.setLayoutParams(lp);
    mRadioButton.setId(paymentradiobuttonid);
    mRadioButton.setClickable(false);      

    setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mRadioButton.setChecked(true);
        }
    });

}

public void setPaymentName(String name) {
    mTextView.setText(name);
}

public void setPaymentLogo(int resId) {
    mImageView.setImageResource(resId);
}

public View getRadioButton() {
    return mRadioButton;
}

}


2个回答

qq_24827089
qq_24827089   2016.09.08 14:45

你都没有把new好的控件addView到父控件中,肯定没显示。

taocgz
taocgz   2016.09.22 17:24

最近忙于其他事,没来的及恢复,我试一下。谢谢。

Csdn user default icon
上传中...
上传图片
插入图片