here is my code, I hope make view like html5 <hr/>
public class Hr extends View {
public Hr(Context context) {
super(context);
ii();
}
public Hr(Context context, AttributeSet attrs) {
super(context, attrs);
ii();
}
void ii() {
setBackgroundColor(col(this, R.color.gray));
ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(MATCH_PARENT, 1);
lp.topMargin = 5;
lp.bottomMargin = 5;
setLayoutParams(lp);
}
}
but when i test it:
<ro.adr.Hr android:layout_width="match_parent" android:layout_height="match_parent"/>
the result is gray block, why lp
doesn't work?
LayoutParams are used by views to tell their parents how they want to be laid out. See ViewGroup Layout Attributes for a list of all child view attributes that this class supports. The base LayoutParams class just describes how big the view wants to be for both width and height.
Create a custom viewGo to View > Workbook Views > Custom Views > Add. In the Name box, type a name for the view. Tip: To make a view easier to identify, you can include the name of the active worksheet in the name of a view. Under Include in view, select the check boxes of the settings that you want to include.
Some examples of default views present in the Android Framework are EditText, TextView, Button, CheckBox, RadioButton, etc. ViewGroup is a special view that can contain other views (called children). We can create custom views and use them in our Application.
The issue is with the order of things that happen when a View
is inflated from layout xml
.
If you go through the code of the LayoutInflater
class, you'll see that the order is:
xml
as attrs
(a particular part of the xml
related to specific ViewGroup
child)View
LayoutParams
created based on the previously obtained attrs
That means that the LayoutParams
you create inside your constructor (lp
) are being overwritten by the LayoutParams
from the xml
(in the 3.
step).
What you can do to fix that is to move your ii()
call to the onAttachedToWindow()
method.
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ii();
}
For custom views, you can override the onMeasure(), something like:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(500,500);
}
and
setMeasuredDimension()
can be used to set the desired dimensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With