Центрируйте элементы HorizontalScrollView, когда его недостаточно для прокрутки
У меня есть макет с HorizontalScrollView
содержащий LinearLayout
для меню, где содержимое надувается с содержанием БД. Это работает хорошо, однако, когда недостаточно элементов для прокрутки HSV
это не занимает всю ширину экрана, которая в идеале должна быть центрирована. т.е. в настоящее время:
| Element 1 Element 2 | <- edge of screen
Вместо:
| Element 1 Element 2 | <- edge of screen
пока еще в состоянии:
| Element 1 Element 2 Element 3 Element 4 Elem| <- edge of screen now scrolling
XML макета:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLinearLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/header"
android:layout_width="fill_parent"
android:layout_height="25dp" >
</TextView>
<ScrollView
android:id="@+id/scroll1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<LinearLayout
android:id="@+id/contentLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="30dp">
<LinearLayout
android:id="@+id/footerLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Со следующим XML, раздуваемым внутри footerLayout:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/footer_content"
android:textSize="18sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:text="FOOTER"
android:singleLine="true" />
Ответы
Ответ 1
Я просто решил эту проблему. Я столкнулся с ним несколько часов назад. Вы должны центрировать HorizontalScrollView в своем родителе и установить его ширину/высоту в wrap_content. Макет, который вы помещаете в HSV, должен иметь свою ширину/высоту, чтобы также обернуть содержимое. Важная часть здесь заключается в том, чтобы не устанавливать гравитацию /layout _gravity на этом макете, или вы можете испытывать (очень раздражающие) проблемы отсечения после раздувания ваших взглядов. Пример ниже содержится в RelativeLayout.
<HorizontalScrollView android:id="@+id/svExample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/rlExample">
<LinearLayout
android:id="@+id/llExample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView >
Ответ 2
У меня была такая же проблема, и, наконец, я получил ее на работу. Вот минимальный пример:
Основной макет деятельности с HorizontalScrollView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true" >
<LinearLayout
android:id="@+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Расположение элементов, которые будут надуты и помещены в представление прокрутки:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="your text" />
</LinearLayout>
И это пример кода для раздувания и добавления элементов:
LinearLayout container = (LinearLayout) findViewById(R.id.container);
LayoutParams elementLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);
int elementCount = 3; // ...or however many you like
for (int i = 0; i < elementCount; i++) {
LinearLayout element = (LinearLayout) getLayoutInflater().inflate(R.layout.element, null);
container.addView(element, elementLayoutParams);
}
В основном это основано на технике растягивания содержимого ScrollViews, объясненной в этой статье Romain Guy.
Однако в этом случае, когда вы добавляете содержимое динамически, другой ключевой момент - установка положительного значения для веса (1f в этом примере) с использованием LayoutParams при добавлении элементов в контейнер. Если у вас есть статический набор элементов, который вы можете включить непосредственно в контейнер, и вам не нужно его раздувать, вы можете указать вес внешнего LinearLayout элементов в XML-макете следующим образом:
android:layout_weight="1"
Но если вы сделаете это динамически, это не сработает, потому что вес сбрасывается до 0 и элементы разрушаются. Следовательно, вам нужно установить его через LayoutParams.
Ответ 3
Ниже приведен самый простой способ для меня.
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<LinearLayout
android:id="@+id/layout_others"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</HorizontalScrollView>
Ответ 4
удалось обойти центрально-горизонтальное отсечение левой стороны:
Горизонтальная панель управления отображением была изменена на:
<LinearLayout
android:id="@+id/footerWrapperLayoutToGetAroundCenteringIssue"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:gravity="center_horizontal">
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_height="fill_parent"
android:layout_width="wrap_content">
<LinearLayout
android:id="@+id/footerLayout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Просто жаль, когда он центрирует их, они распределены неравномерно.
Если у кого-нибудь есть идеи, пожалуйста, дайте мне знать.
Ответ 5
присвойте wieght 1 текстовому виду в увеличенном виде и сделайте ширину wrapcontent