Стиль Android ICS для полной ширины Минималистские нижние кнопкиПросмотры - PullRequest
6 голосов
/ 27 марта 2012

Я хочу сделать несколько кнопок, которые выглядят следующим образом: ICS Buttons

Я выглядел довольно сложно для предустановленных ICS-кнопок в пакете android.widget, но не могу их найти.Я думаю, что должен быть легкий путь, так как они кажутся тематическими для всей версии ОС.Если кто-нибудь знает, как сделать так, чтобы пуговицы выглядели так, я был бы счастливым туристом.

Ответы [ 4 ]

17 голосов
/ 20 апреля 2012

В случае, если вы ищете макет кнопки XML в Android ICS, как показано на следующем снимке экрана, вот макет XML, который я нашел из исходного кода ОС Android.

App uninstall screenshot on Android 4.0

<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- OK confirm and cancel buttons.  -->
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:divider="?android:attr/dividerHorizontal"
        android:showDividers="beginning"
        android:paddingTop="16dip">

    <LinearLayout
            style="?android:attr/buttonBarStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:measureWithLargestChild="true">

        <LinearLayout android:id="@+id/leftSpacer"
                android:layout_weight="0.25"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:visibility="gone" />

        <Button android:id="@+id/cancel_button"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_weight="1"
                android:text="@string/cancel"
                android:maxLines="2"
                style="?android:attr/buttonBarButtonStyle" />

        <Button android:id="@+id/ok_button"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_weight="1"
                android:text="@string/install"
                android:maxLines="2"
                android:filterTouchesWhenObscured="true"
                style="?android:attr/buttonBarButtonStyle" />

        <LinearLayout android:id="@+id/rightSpacer"
                android:layout_width="0dip"
                android:layout_weight="0.25"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:visibility="gone" />

    </LinearLayout>
</LinearLayout>
3 голосов
/ 28 марта 2012

Немного поигрался по этому вопросу.Сделал решение на основе linearLayouts с 1dp-представлениями в качестве разделителей и прозрачного фона, чтобы минимализм выглядел на кнопках.

enter image description here

Мы хотим, чтобы кнопки меняли внешний вид в зависимости от состояниякнопка.(Подробнее об этом здесь привет материал учебник ).Мы меняем цвет фона таким образом, чтобы пользователь получал указание при нажатии кнопки.

borderless_background.xml (помещается в папку для рисования)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <shape>
            <solid android:color="#33b5e5" />
        </shape>
    </item>

    <item android:state_focused="true">
        <shape>
            <solid android:color="#0099cc" />
        </shape>
    </item>

    <item>
        <shape>
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

</selector>

Затем в main.xml будет использоваться borderless_backgroundфайл, см. тег android: background для кнопок в следующем коде

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="8dp"
    android:orientation="vertical"
>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:gravity="center"
        android:layout_weight="1.0"
        android:textSize="14sp"
        android:text="@string/borderless" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:textSize="12sp"
        android:autoLink="web"
        android:text="@string/source1" />

    <View
        android:id="@+id/horizontal_divider1"
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="48dp"
            android:layout_weight="1.0"
            android:background="@drawable/borderless_background"
            android:textColor="@android:color/white"
            android:textSize="16sp"
            android:text="Cancel"
            android:onClick="cancel" />

        <View
            android:id="@+id/vertical_divider"
            android:layout_width="1dip"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:layout_height="fill_parent"
            android:background="@android:color/darker_gray" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="48dp"
            android:layout_weight="1.0"
            android:background="@drawable/borderless_background"
            android:textColor="@android:color/white"
            android:textSize="16sp"
            android:text="Next"
            android:onClick="next" />
    </LinearLayout>

    <View
        android:id="@+id/horizontal_divider2"
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray" />

</LinearLayout>

Есть предупреждения относительно производительности из-за вложенных линейных компоновок, но на планшете, на котором я тестировал, все работает нормально, поэтому мне леньисправить это.Исправление, вероятно, будет основано на относительной компоновке или компоновке сетки.

3 голосов
/ 27 марта 2012

Если вы хотите сделать это на всех устройствах (и версиях Android), вам нужна кнопка без фона или сплошной фон с границами сверху и снизу.

Единственный способ добавитьГраницы правильно в Android это использовать инструмент, который поставляется с Android SDK или ADT под названием draw9patch.Это простой маленький инструмент, который сделает работу.Если вам нужна помощь с его фактическим использованием, лучше всего искать видео на YouTube, поскольку его может быть сложно использовать в первый раз.

Draw 9-patch

1 голос
/ 01 июня 2012

Я нашел очень простое решение, которое:

  • добавляет прозрачные иконки
  • имеет горизонтальную верхнюю границу
  • имеет вертикальный разделитель между кнопками
  • не имеет нижней границы

Источник: https://gist.github.com/2373644

Содержание:

<!--
  A button bar is a set of buttons at the bottom of an activity.
  An example is an AlertDialog with OK/Cancel buttons.

  Note that something similar can be accomplished using a
  split action bar and text-only action buttons, but this is an
  alternate presentation that's often preferred.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="?android:attr/dividerHorizontal"
    android:showDividers="middle">

    <TextView android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Hello World" />

    <LinearLayout style="?android:attr/buttonBarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button style="?android:attr/buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="One" />

        <Button style="?android:attr/buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Two" />
    </LinearLayout>
</LinearLayout>
...