如何在Android中以编程方式初始化自定义组件?

时间:2019-05-18 02:25:49

标签: java android custom-component

我已经知道如何在xml中使用自定义组件。现在,我正在尝试以编程方式调用一个。我还没有找到有关此的任何教程,所以我尝试这样做,就像我们以编程方式声明视图一样。我偶然发现的一个问题是,如何获得传递给构造函数的AttributeSet?我不知道如何获取或创建该内容以将其传递给自定义组件。

这是我的自定义组件类。

public class CheckOutItem extends ConstraintLayout {
    public Context ctx;
    public Paint mPaint;
    public Rect mRect;
    int mSquareColor;
    public ImageView imgThumbnail;
    public TextView lblAbbrev, lblFullName;
    public ConstraintLayout lytMain;
    String TAG = "sharePOS";

    public CheckOutItem(Context context) {
        super(context);
        ctx = context;
        init(null);
    }

    public CheckOutItem(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.checkout_item, this);
        ctx = context;

        init(attrs);
    }

    public CheckOutItem(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ctx = context;
        init(attrs);
    }

    private void init(@Nullable AttributeSet set){
        //inflate(ctx, R.layout.checkout_item, this);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mRect = new Rect();

        if(set == null){
            return;
        }

        TypedArray ta = getContext().obtainStyledAttributes(set, R.styleable.CheckOutItem);

        this.imgThumbnail = findViewById(R.id.imgItemThumbnail);
        this.lblAbbrev = findViewById(R.id.lblItemAbbrevName);
        this.lblFullName = findViewById(R.id.lblItemFullName);
        this.lytMain = findViewById(R.id.lytMain);

        this.lblAbbrev.setText(ta.getText(R.styleable.CheckOutItem_abbrevText));
        this.lblAbbrev.setTextSize(ta.getDimension(R.styleable.CheckOutItem_abbrevTextSize, 1f));
        this.lblAbbrev.setTextColor(ta.getColor(R.styleable.CheckOutItem_abbrevTextColor, Color.BLACK));

        this.lblFullName.setText(ta.getText(R.styleable.CheckOutItem_fullNameText));
        this.lblFullName.setTextSize(ta.getDimension(R.styleable.CheckOutItem_fullNameTextSize, 1f));
        this.lblFullName.setTextColor(ta.getColor(R.styleable.CheckOutItem_fullNameTextColor, Color.BLACK));
        this.lblFullName.setBackgroundColor(ta.getColor(R.styleable.CheckOutItem_fullNameBackgroundColor, Color.WHITE));

        this.lytMain.setBackgroundColor(ta.getColor(R.styleable.CheckOutItem_mainBackgroundColor, Color.LTGRAY));
        this.lytMain.setBackground(ta.getDrawable(R.styleable.CheckOutItem_mainBackgroundDrawable));

        ta.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mRect.left = 0;
        mRect.right = getWidth();
        mRect.top = 0;
        mRect.bottom = getHeight();

        Log.d(TAG, "rect: " + mRect);
        canvas.drawRect(mRect, mPaint);
    }
}

更新:

如何在自定义组件中设置边距?常规LayoutParamssetMargins()似乎不起作用。

0 个答案:

没有答案