To my knowledge, it will only be possible to implement this behavior in a class inherited from Textview.
public class TextViewWithParentTopMargin extends android.support.v7.widget.AppCompatTextView {
public TextViewWithParentTopMargin(Context context) {
super(context);
}
public TextViewWithParentTopMargin(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public TextViewWithParentTopMargin(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
ViewGroup parent = (ViewGroup) getParent();
ViewGroup.MarginLayoutParams parentLayoutParams = (ViewGroup.MarginLayoutParams)parent.getLayoutParams();
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams)getLayoutParams();
int leftMargin = layoutParams.leftMargin;
int topMargin = parentLayoutParams.topMargin;//Atribui valor do pai ao TextView
int rightMargin = layoutParams.rightMargin;
int bottomMargin = layoutParams.bottomMargin;
layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
}
}
In the method onMeasure()
get Marginlayoutparams from the father and assign his margins to the margins of Textview.
In the example given only was attributed to topMargin
.
The xml will look like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="16dp"
android:layout_marginTop="50dp">
<sua.package.TextViewWithParentTopMargin
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/quantity"
android:textAllCaps="true"/>
...
</LinearLayout>
Textview will be automatically applied (will inherit) the value of layout_marginTop
from his father to his top margin.
Thank you so much! That’s exactly what I needed!
android:
at the beginning of the sentence?– Nakamoto
@Nakamoto I don’t see how this is what you asked.
– ramaral
Not in this case, that’s right.
– Jonathan Souza