I am trying to create a custom view group and created it successfully but unable to set margin to an child of viewgroup like editext Following is my code,
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);
}
}
Whenever I try to set margin to the element I got the following exception,
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)
It happens, whenever I add the following code,
measureChildWithMargins(
materialEditText,0,0,20,0);
I have started by looking at the following examples but unable to solve my issue,
Measure, Layout, Draw, Repeat: Custom Views and ViewGroups by Huyen Tue Dao