As far as I know, it will only be possible to implement this behavior in a TextView inheritance class.
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 onMeasure()
method, get the parent's MarginLayoutParams and assign their margins to the edges of the TextView.
In the given example, only topMargin
was assigned.
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 automatically apply (inherit) the value of layout_marginTop
from parent to its top margin .