Android: последняя строка текста отключена
У меня есть горизонтальный LinearLayout
, содержащий a TextView
, за которым следует a Spinner
рядом с ним. Этот LinearLayout
динамически накачивается несколько раз в фиксированном вертикальном LinearLayout
, содержащемся в RelativeLayout
.
Проблема заключается в том, что, поскольку я переключился с Theme.light
на Theme.holo.light
, последняя строка TextView
сокращается вдвое. Это происходит, когда динамический текст длинный и охватывает более одной строки.
![enter image description here]()
Я смог исправить это, добавив нижнее дополнение к горизонтальному LinearLayout
, содержащему TextView
и Spinner
.
Это не похоже на исправление, а скорее на взломы. Может кто-нибудь, пожалуйста, дайте мне несколько советов о том, как правильно это исправить?
Я также прочитал некоторые другие вопросы, но никто, кажется, не помогает.
Горизонтальная линейная компоновка:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:text="TextView"/>
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Относительная компоновка, где над компоновкой динамически раздувается линейная компоновка с id ll2_7:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/relLayoutButtonNext"
android:layout_below="@id/textView1" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp" >
<TextView
android:id="@+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="30dp"
android:text="2.7" />
<TextView
android:id="@+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_toRightOf="@id/textView10"
android:text="@string/question2_7" />
<LinearLayout
android:id="@+id/ll2_7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView11"
android:layout_below="@+id/textView11"
android:orientation="vertical" android:layout_marginBottom="20dp">
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
EDIT:
Вот полный макет xml для выше:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
style="@style/question_section_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="@string/question2_header" />
<RelativeLayout
android:id="@+id/relLayoutButtonNext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/bottomBar"
android:paddingBottom="3dp"
android:paddingLeft="50dp"
android:paddingRight="50dp"
android:paddingTop="3dp" >
<Button
android:id="@+id/buttonNext"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:onClick="nextStep"
android:text="Next Section"
android:textSize="20sp" />
<Button
android:id="@+id/buttonPrevious"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="previousStep"
android:text="Previous Section"
android:textSize="20sp" />
</RelativeLayout>
<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/relLayoutButtonNext"
android:layout_below="@id/textView1" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp" >
<TextView
android:id="@+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="30dp"
android:text="2.7" />
<TextView
android:id="@+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_toRightOf="@id/textView10"
android:text="@string/question2_7" />
<LinearLayout
android:id="@+id/ll2_7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView11"
android:layout_below="@+id/textView11"
android:orientation="vertical" android:layout_marginBottom="20dp">
</LinearLayout>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView10"
android:layout_below="@+id/ll2_7"
android:text="2.8" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ll2_7"
android:layout_toRightOf="@+id/textView10"
android:text="@string/question2_8" android:layout_marginBottom="10dp"/>
<LinearLayout
android:id="@+id/ll2_8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView3"
android:layout_below="@+id/textView3"
android:layout_marginBottom="20dp"
android:orientation="vertical" >
</LinearLayout>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/ll2_8"
android:text="2.9" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ll2_8"
android:layout_toRightOf="@+id/textView10"
android:text="@string/question2_9" android:layout_marginBottom="10dp"/>
<LinearLayout
android:id="@+id/ll2_9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView5"
android:layout_toRightOf="@+id/textView10"
android:orientation="vertical" android:layout_marginBottom="20dp">
</LinearLayout>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/ll2_9"
android:text="2.10" />
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ll2_9"
android:layout_toRightOf="@+id/textView10"
android:text="@string/question2_10" android:layout_marginBottom="10dp"/>
<LinearLayout
android:id="@+id/ll2_10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView7"
android:layout_marginBottom="20dp"
android:layout_toRightOf="@+id/textView10"
android:orientation="vertical" >
</LinearLayout>
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView6"
android:layout_below="@+id/ll2_10"
android:text="2.11" />
<TextView
android:id="@+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ll2_10"
android:layout_toRightOf="@+id/textView10"
android:text="@string/quesiton2_11" android:layout_marginBottom="10dp"/>
<LinearLayout
android:id="@+id/ll2_11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView9"
android:layout_below="@+id/textView9"
android:orientation="vertical" android:layout_marginBottom="20dp">
</LinearLayout>
<TextView
android:id="@+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView8"
android:layout_below="@+id/ll2_11"
android:text="2.11.1" />
<TextView
android:id="@+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ll2_11"
android:layout_toRightOf="@+id/textView10"
android:text="@string/question2_11_1" android:layout_marginBottom="10dp"/>
<LinearLayout
android:id="@+id/ll2_11_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView13"
android:layout_toRightOf="@+id/textView10"
android:orientation="vertical" android:layout_marginBottom="20dp">
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
Ответы
Ответ 1
Я столкнулся с такой же проблемой отсечения, как показано на скриншоте. Это вызвано выравниванием базовой линии в горизонтальном LinearLayout
. TextView
и Spinner
имеют разные базовые линии из-за разницы размеров шрифта. Чтобы устранить проблему, необходимо отключить выравнивание базовой линии для макета, установив:
android:baselineAligned="false"
или в коде:
layout.setBaselineAligned(false);
Ответ 2
Попробовав миллион разных вещей, я думаю, что у меня есть ответ.
Я применил LayoutGravity
к элементу TextView:
android:layout_gravity="fill"
Кажется, нужно решить все проблемы отсечения, которые у меня были. Надеюсь, это поможет кому-то с той же проблемой.
Ответ 3
У меня была та же проблема, и я обнаружил, что просто добавив
android:includeFontPadding="false"
окончательная строка текста больше не ограничивала свои декодеры.
Ответ 4
Я добавил некоторое фиктивное пространство после текста, добавив
textView.setText(firstString+"\n");
Я пробовал все остальные решения. Но это было единственное решение, которое работало для меня
Ответ 5
Поместите проблемный текст внутри рамки. Я думаю, что текстовое представление не рассчитано правильно из-за представления сестры, Spinner.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<FrameLayout
android:layout_width="150dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:text="TextView"/>
</FrameLayout>
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Ответ 6
Когда это произойдет, вы должны убедиться, что TextView
не растет больше, чем контейнер -
Если для параметра TextView
установлено значение wrap_content
, и контейнер (или контейнер-предка) не оставляет места для того, чтобы TextView
, чтобы вырасти в него, может быть закрыт.
Если это не так, также возможно, что onMeasure()
TextView
иногда неправильно оценивает хвосты букв, нелатинских символов или эффекты от текста, выделенного курсивом. Вы можете исправить это, установив глобальный стиль для TextView
, чтобы он был поднят без необходимости изменения всей базы кода:
Убедитесь, что вы используете приложение/действия для использования специальной темы следующим образом:
<style name="Custom" parent="@android:style/Theme.Light">
<item name="android:textViewStyle">@style/Custom.Widget.TextView</item>
</style>
<style name="Custom.Widget.TextView" parent="@android:style/Widget.TextView">
<item name="android:gravity">fill</item>
<item name="android:padding">1sp</item>
</style>
Ответ от @Rynadt был действительно полезен для выхода на вышеперечисленный этап. Установка силы тяжести текста внутри представления обеспечивает на некоторых устройствах, что окклюзия никогда не происходит (текст правильно установлен внутри представления), а другие - с помощью дополнений sp-значения, гарантирует, что хвосты и т.д. Учитываются с определенным значением TextSize.
Ответ 7
Я нашел другое решение, расширив TextView и добавив пользовательский класс следующим образом:
public class AdaptingTextView extends TextView {
public AdaptingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public AdaptingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AdaptingTextView(Context context) {
super(context);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// set fitting lines to prevent cut text
int fittingLines = h / this.getLineHeight();
if (fittingLines > 0) {
this.setLines(fittingLines);
}
}
}
Ответ 8
попробуйте удалить андроид: paddingBottom = "20dp"
из
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp" >
Ответ 9
Мое решение было близко к принятому, но мне пришлось изменить его на
android:layout_gravity="fill_vertical"
вместо этого. В противном случае другие строки также были бы растянуты с добавлением разрывов строк в случайных местах. Например, самая большая строка имела 4 строки, поэтому другая строка была изменена с
this is a testphrase
к
thi
s is
a testph
rase
Ответ 10
Если у вас есть эта проблема, а ваш TextView
находится внутри RelativeLayout
, попробуйте переключить RelativeLayout
на LinearLayout
.
Это исправило проблему для меня
Ответ 11
Вы можете использовать глобальный приемник макетов для TextView в любом виде ViewGroup.
final TextView dSTextView = (TextView)findViewById(R.id.annoyingTextView);
dSTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
dSTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
float lineHeight = dSTextView.getLineHeight();
int maxLines = (int) (dSTextView.getHeight() / lineHeight);
if (dSTextView.getLineCount() != maxLines) {
dSTextView.setLines(maxLines);
}
}
});
Подробнее об этом можно узнать здесь
Ответ 12
getViewTreeObserver().addOnGlobalLayoutListener
не работает в режиме ресайклера. Если вы используете ресайклеров, используйте View.addOnLayoutChangeListener
:
Я обнаружил, что эллипсинг I, определенный для textView
в xml, не всегда отражается, поэтому я программно его устанавливаю перед переназначением свойства text. Это сработало для меня.
textView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
textView.removeOnLayoutChangeListener(this);
float lineHeight = textView.getLineHeight();
int maxLines = (int) (textView.getHeight() / lineHeight);
if (textView.getLineCount() != maxLines) {
textView.setLines(maxLines);
textView.setEllipsize(TextUtils.TruncateAt.END);
// Re-assign text to ensure ellipsize is performed correctly.
textView.setText(model.getText());
}
}
});
Ответ 13
У меня есть эта же проблема, и это очень раздражает.
Это происходит только с арабским текстом.
Если вы сделаете метку многострочной и добавив \n
в конец строки, она исправит ее, но проблема в том, что между этой меткой и объектом ниже будет большой разрыв к тому, что это поле теперь имеет новую пустую строку под ним.
Пользовательский элемент управления можно сделать, чтобы обойти это. Но в целом это раздражающая ошибка.
Ответ 14
Я думаю, что вы можете сделать это очень мало, чтобы изменить это поведение, изменив макеты. Как я понял, некоторые методы работают только в некоторых случаях. Я думаю, что это зависит от всей иерархии раскладок и не является решением одного размера. Я также заметил, что это происходит, особенно если у вас есть другой шрифт, который вы хотите установить в TextView.
Правильный метод выстрела, который я экспериментировал и тестировал, заключается в том, что вы можете установить атрибуты шрифта в коде после раздутия представления. Я предполагаю, что у вас есть шрифт в папке assets/fonts, которую вы хотите.
Например, в фрагменте:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_view, container, false);
TextView tv = (TextView)view.findViewById(R.id.text_view);
tv.setText("Insert text that needs to be displayed");
AssetManager assetManager = getContext().getAssets();
Typeface typeFace = Typeface.createFromAsset(assetManager, "Fonts/OpenSans-Light.ttf");
tv.setTypeface(typeFace , 0); // 0 is normal font
tv.setPadding(10, 0, 10, 0); // This is not mandatory
}
И в Управлении:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(Resource.Layout.main_activity);
TextView tv = (TextView)this.findViewById(R.id.text_view);
tv.setText("Insert text that needs to be displayed");
AssetManager assetManager = getContext().getAssets();
Typeface typeFace = Typeface.createFromAsset(assetManager, "Fonts/OpenSans-Light.ttf");
tv.setTypeface(typeFace , 0); // 0 is normal font
tv.setPadding(10, 0, 10, 0); // This is not mandatory
}
Ответ 15
Лучшим обходным путем для этого является добавление фиктивного представления желаемой высоты (т.е. это добавит саму по себе) внизу вашего представления.
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" >
<View
android:layout_width="match_parent"
android:layout_height="30dp"/>
</TableRow>
Как и в моем случае, я добавил еще одну таблицу в нижней части представления. Надеюсь, это может помочь кому-то.
Ответ 16
Я знаю это так поздно, но для меня это работает как прелесть.
добавьте этот код в свой textview
android:ellipsize="marquee"
android:layout_weight="1"
Ответ 17
Добавьте отступы внизу текстового представления:
android:paddingBottom="24dp"
Ответ 18
Я, наконец, исправил это!
Я пытаюсь добавить String в TextView в службе, а затем вызовет scrollTo(), последняя строка будет отключена!
ScrollTo() должен быть вызван в "Runnable", например:
private ScrollView mScrollView;
public void scrollToBottom()
{
mScrollView = (ScrollView) findViewById(R.id.debug_textview_scrollview);
mScrollView.post(new Runnable()
{
public void run()
{
mScrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
Я думаю, потому что в моменте вызова scrollTo() в службе обновление TextView не готово.