нет гравитации для scrollview. как сделать содержимое внутри scrollview в качестве центра
Я хочу, чтобы содержимое внутри scrollView было в центре.
<ScrollView
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="12dp"
android:paddingBottom="20dp"
android:scrollbarStyle="outsideOverlay"
android:layout_gravity="center" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="check"
android:gravity="center_vertical|center_horizontal"/>
</ScrollView>
Примечание: нет android:gravity атрибут для scrollvew.
любая соль:-
6 ответов:
у меня была та же проблема и, наконец, понял это. Это для вертикали
ScrollView.положить
ScrollViewвнутриRelativeLayoutцентр вRelativeLayout. Для того, чтобы это сработало, вашScrollViewдолжно бытьandroid:layout_height="wrap_content"вот как должен выглядеть окончательный код:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ScrollView android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" > <LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_parent" android:layout_height="wrap_content" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="b1"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="b2"/> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="b3"/> </LinearLayout> </ScrollView> </RelativeLayout>
Как насчет этого?
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="12dp" android:paddingBottom="20dp" android:scrollbarStyle="outsideOverlay" > <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_gravity="center" android:gravity="center"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="check" android:gravity="center_vertical|center_horizontal"/> </LinearLayout> </ScrollView>
мне кажется более элегантным решением было бы использовать
ScrollView' sandroid:fillViewportсобственность. АScrollViewнемного отличается в том, как он обрабатывает его содержимое (может иметь только один), даже если вы установитеmatch_parent(fill_parent) кScrollViewэто не даст такого большого расстояния для его представления содержимого, вместо этого поведение по умолчанию дляScrollViewчтобы обернуть содержимое независимо от того, что вы укажете для этого представления. Чтоandroid:fillViewportне скажуScrollViewрастянуть его содержимое, чтобы заполнить видовой экран (http://developer.android.com/reference/android/widget/ScrollView.html#attr_android:fillViewport)Так что в данном случае вашLinearLayoutбудет растягиваться в соответствии с видовым окном, и если высота идет за видовым окном, то он будет прокручиваться, что именно то, что вы хотите!принятый ответ не будет работать должным образом, когда содержание выходит за пределы
ScrollViewпотому что он по-прежнему будет центрировать представление содержимого, сначала заставляя его отрезать часть представления, и элементScrollViewцентрированный в другом макете работает, но просто не чувствует себя правильно, кроме того, я думаю, что это также приведет к ошибке lint (бесполезный родитель или что-то в этом роде).попробуйте что-то вроде этого:
<ScrollView android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="12dp" android:paddingBottom="20dp" android:scrollbarStyle="outsideOverlay" android:fillViewport="true"> <LinearLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="check" /> </LinearLayout> </ScrollView>просто помните, что причина, по которой он центрируется здесь сейчас, заключается в
android:gravityнаLinearLayoutСScrollViewрастянетLinearLayoutтак что имейте это в виду, в зависимости от того, что вы добавите к макету.еще одно хорошее чтение на
ScrollViewхотя не о центрировании, а оfillViewportis http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/
для @Patrick_Boss-то, что остановило контент от резки в моем приложении, состояло в том, чтобы изменить гравитацию и layout_gravity на center_horizontal для LinearLayout.
это сработало для меня...но не уверен, что это сработает для вас.
модификация ответа @ Ghost -
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="12dp" android:paddingBottom="20dp" android:scrollbarStyle="outsideOverlay" > <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_gravity="center_horizontal" android:gravity="center_horizontal"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="check" android:gravity="center_vertical|center_horizontal"/> </LinearLayout> </ScrollView>
используйте этот атрибут в ScrollView
android:fillViewport="true"пример
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbarStyle="outsideOverlay" android:fillViewport="true" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!--Your Code goes here--> </RelativeLayout> </ScrollView>убедитесь, что использовать один ребенок в ScrollView так же, как в приведенном выше примере, который является Relativelayout.
одна вещь, чтобы рассмотреть то, что не установить. Убедитесь, что дочерние элементы управления, особенно элементы управления EditText, не имеют набора свойств RequestFocus. Это может быть одно из последних интерпретируемых свойств макета, и оно переопределит параметры гравитации на своих родителях (макет или ScrollView).