Repeated background affects the height of TextViews

I have an image that I want to repeat on the x axis so that it matches the width.

repeating_section_header.xml:

<?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/table_section_header_light" android:tileMode="repeat" /> 

so far so good. Now I set this as the background of the TextView :

 <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/row_headline_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/repeating_section_header" android:gravity="left|center_vertical" android:textColor="@color/white" android:textSize="14sp" android:textStyle="bold"/> 

But now the height of the TextViews is the height of @drawable/table_section_header_light , even if I set the height of the TextViews to wrap_content .

Think about how to fix it (make the TextViews height to wrap the content)

+4
source share
2 answers

One way to do this is to programmatically determine the height of the text field with only text, as well as fix the height and set the background. Thus, it will adjust the height of your text view depending on how many lines are used.

Java:

 TextView v = (TextView) findViewById(R.id.row_headline_text); v.setText("<your text here>"); v.measure(android.view.View.MeasureSpec.UNSPECIFIED, android.view.View.MeasureSpec.UNSPECIFIED); android.view.ViewGroup.LayoutParams params = v.getLayoutParams(); params.height = v.getMeasuredHeight(); v.setLayoutParams(params); v.setBackgroundResource(R.drawable.table_section_header_light); 

XML:

 <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/row_headline_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="left|center_vertical" android:textColor="@color/white" android:textSize="14sp" android:textStyle="bold" /> 
0
source

If you agree with this technique, try:

  • Wrap a TextView in a RelativeLayout.
  • Add RelativeLayout as the first child. (let TextView be the second child)
  • Remove your background from TextView to new View
  • Set the layout options for your TextView (AlignLeft, AlignRight, AlignTop, AlignBottom) at @+id/row_headline_text

That should work. If your parent TextView is already a RelativeLayout, you will not need a new RelativeLayout.

0
source

Source: https://habr.com/ru/post/1502784/


All Articles