将边距设置为自定义视图组项目视图喜欢edittext

时间:2018-02-19 13:10:03

标签: android android-custom-view viewgroup android-viewgroup android-layoutparams

我正在尝试创建自定义视图组并成功创建它但无法为视图组的子项设置边距,如editext 以下是我的代码,

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;

import mp.R;

public class EditTextLoader extends ViewGroup {

private EditText materialEditText;
private ProgressBar progressBar;
private ImageView imgErrorRefresh;

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

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

public EditTextLoader(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
}


private void init(@NonNull Context context) {
    setClipToPadding(false);

    materialEditText = new EditText(context);
    materialEditText.setGravity(Gravity.START);
    materialEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
    materialEditText.setHint(context.getString(R.string.vShutt_textPickup));
    addView(materialEditText);

    progressBar = new ProgressBar(context);
    addView(progressBar);

    imgErrorRefresh = new ImageView(context);
    imgErrorRefresh.setImageResource(R.drawable.editext_success);
    addView(imgErrorRefresh);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    widthMeasureSpec = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    int height = 0;

    // 2. Measure the ProfilePhoto
    measureChild(imgErrorRefresh, widthMeasureSpec, heightMeasureSpec);

    height = Math.max(materialEditText.getMeasuredHeight(), height);
    measureChild(materialEditText, widthMeasureSpec, heightMeasureSpec);

    setMeasuredDimension(widthMeasureSpec, height);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    int height = getHeight();
    int leftWidthImage = right - imgErrorRefresh.getMeasuredWidth();
    progressBar.layout(leftWidthImage, 0, right, height);
    materialEditText.layout(0, 0, leftWidthImage - 20, height);
}

}

每当我尝试为元素设置边距时,我得到以下异常,

java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams
                                                                        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6593)
                                                                        at mp.EditTextLoader.onMeasure(EditTextLoader.java:73)

只要我添加以下代码,就会发生这种情况,

    measureChildWithMargins(
            materialEditText,0,0,20,0);

我从查看以下示例开始,但无法解决我的问题,

Measure, Layout, Draw, Repeat: Custom Views and ViewGroups by Huyen Tue Dao

Custom ViewGroups by Sriram

0 个答案:

没有答案