Подтвердить что ты не робот

Как создать стандартные кнопки Borderless (как указано в руководстве по проектированию)?

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

Здесь ссылки на руководящие принципы проектирования:

enter image description here

4b9b3361

Ответ 1

Чтобы устранить некоторую путаницу:

Это делается в 2 этапа: установка атрибута фона кнопки android: attr/selectableItemBackground создает кнопку с обратной связью, но не имеет фона.

android:background="?android:attr/selectableItemBackground"

Линия для разделения кнопки без полей на остальной части вашего макета выполняется с помощью представления с фоном android: attr/dividerVertical

android:background="?android:attr/dividerVertical"

Для лучшего понимания здесь находится макет комбинации кнопок ОК/Отмена без полей внизу экрана (например, на правом рисунке выше).

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignParentBottom="true">
        <View
            android:layout_width="match_parent"
            android:layout_height="1dip"
            android:layout_marginLeft="4dip"
            android:layout_marginRight="4dip"
            android:background="?android:attr/dividerVertical"
            android:layout_alignParentTop="true"/>
        <View
            android:id="@+id/ViewColorPickerHelper"
            android:layout_width="1dip"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="4dip"
            android:layout_marginTop="4dip"
            android:background="?android:attr/dividerVertical" 
            android:layout_centerHorizontal="true"/>
        <Button
            android:id="@+id/BtnColorPickerCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@id/ViewColorPickerHelper"
            android:background="?android:attr/selectableItemBackground"
            android:text="@android:string/cancel" 
            android:layout_alignParentBottom="true"/>
        <Button
            android:id="@+id/BtnColorPickerOk"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="?android:attr/selectableItemBackground"
            android:text="@android:string/ok" 
            android:layout_alignParentBottom="true" 
            android:layout_toRightOf="@id/ViewColorPickerHelper"/>
    </RelativeLayout>

Ответ 3

Поздний ответ, но много просмотров. Поскольку API < 11 еще не умер, потому что заинтересованные здесь трюки.

Пусть ваш контейнер имеет нужный цвет (может быть прозрачным). Затем дайте кнопкам селектор с прозрачным цветом по умолчанию и некоторым цветом при нажатии. Таким образом, у вас будет прозрачная кнопка, но при нажатии будет изменен цвет (например, голо). Вы также можете добавить анимацию (например, holo's). Селектор должен быть примерно таким:

res/drawable/selector_transparent_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" 
          android:exitFadeDuration="@android:integer/config_shortAnimTime">
     <item android:state_pressed="true"
         android:drawable="@color/blue" />

   <item android:drawable="@color/transparent" />
</selector>

И кнопка должна иметь android:background="@drawable/selector_transparent_button"

PS: пусть у контейнера есть разделители (android:divider='@android:drawable/... для API < 11)

PS [Новички]: вы должны определить эти цвета в значениях/colors.xml

Ответ 4

Для тех, кто хочет кнопки без полей, но все же анимированные при нажатии. Добавьте это в кнопку.

style="?android:attr/borderlessButtonStyle"

Если вам нужен разделитель/линия между ними. Добавьте это в линейный макет.

style="?android:buttonBarStyle"

Сводка

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:orientation="horizontal"
   style="?android:buttonBarStyle">

    <Button
        android:id="@+id/add"
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/add_dialog" 
        style="?android:attr/borderlessButtonStyle"
        />

    <Button
        android:id="@+id/cancel"
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/cancel_dialog" 
        style="?android:attr/borderlessButtonStyle"
        />

</LinearLayout>

Ответ 5

Для стиля материала добавьте style="@style/Widget.AppCompat.Button.Borderless" при использовании библиотеки AppCompat.

Ответ 6

Из источника iosched app Я придумал этот класс ButtonBar:

/**
 * An extremely simple {@link LinearLayout} descendant that simply reverses the 
 * order of its child views on Android 4.0+. The reason for this is that on 
 * Android 4.0+, negative buttons should be shown to the left of positive buttons.
 */
public class ButtonBar extends LinearLayout {

    public ButtonBar(Context context) {
        super(context);
    }

    public ButtonBar(Context context, AttributeSet attributes) {
        super(context, attributes);
    }

    public ButtonBar(Context context, AttributeSet attributes, int def_style) {
        super(context, attributes, def_style);
    }

    @Override
    public View getChildAt(int index) {
        if (_has_ics)
            // Flip the buttons so that "OK | Cancel" becomes "Cancel | OK" on ICS
            return super.getChildAt(getChildCount() - 1 - index);

        return super.getChildAt(index);
    }

    private final static boolean _has_ics = Build.VERSION.SDK_INT >= 
                                        Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}

Это будет LinearLayout, в которое входят кнопки "ОК" и "Отмена", и будет обрабатывать их в соответствующем порядке. Затем поместите это в макет, который вы хотите, кнопки в:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:divider="?android:attr/dividerHorizontal"
          android:orientation="vertical"
          android:showDividers="middle">
    <!--- A view, this approach only works with a single view here -->
    <your.package.ButtonBar style="?android:attr/buttonBarStyle"
        android:id="@+id/buttons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1.0">
        <Button style="?android:attr/buttonBarButtonStyle"
            android:id="@+id/ok_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/ok_button" />
        <Button style="?android:attr/buttonBarButtonStyle"
            android:id="@+id/cancel_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/cancel_button" />
    </your.package.ButtonBar>
</LinearLayout>

Это дает вам вид диалога с кнопками без полей. Эти атрибуты можно найти в res в рамках. buttonBarStyle выполняет вертикальный делитель и отступы. buttonBarButtonStyle устанавливается как borderlessButtonStyle для темы Holo, но я считаю, что это должен быть самый надежный способ отображения, поскольку структура хочет отобразить его.

Ответ 7

Посмотрите на атрибуты темы buttonBarStyle, buttonBarButtonStyle и borderlessButtonStyle.

Ответ 8

Вы также можете создавать кнопки без полей через код:

TypedValue value= new TypedValue();
getApplicationContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, value, true);
 myButton.setBackgroundResource(value.resourceId);

Ответ 9

Для тех, кто хочет программно создать кнопку без полей для API >= 8

ImageButton smsImgBtn = new ImageButton(this);
//Sets a drawable as the content of this button
smsImgBtn.setImageResource(R.drawable.message_icon);    
//Set to 0 to remove the background or for bordeless button
smsImgBtn.setBackgroundResource(0);

Ответ 10

Другим решением, которое должно работать как на старой, так и на новой платформе Android, является использование

android:background="@android:color/transparent"

для представления Button. Но после добавления кнопки выше строки не будет отображаться обратная связь.

Чтобы обеспечить обратную связь, добавьте следующий код в класс Activity

button.setOnTouchListener(new View.OnTouchListener() {          
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:    
                ((Button)view).setBackgroundColor(Color.LTGRAY);
                break;
            case MotionEvent.ACTION_UP:
                ((Button)view).setBackgroundColor(Color.TRANSPARENT);
        }
        return false;
    }
});

Его работа прекрасна для меня.

Ответ 11

Для тех, кто все еще ищет:

наследуйте свой стиль для кнопок Holo:

<style name="yourStyle" parent="@android:style/Holo.ButtonBar">
  ...
</style>

или Холо:

<style name="yourStyle" parent="@android:style/Holo.Light.ButtonBar">
  ...
</style>

и для кнопок Holo без полей:

<style name="yourStyle" parent="@android:style/Widget.Holo.Button.Borderless.Small">
  ...
</style>

или Холо:

<style name="yourStyle" parent="@android:style/Widget.Holo.Light.Button.Borderless.Small">
  ...
</style>

Ответ 12

Используйте приведенный ниже код в вашем XML файле. Используйте android: background = "# 00000000", чтобы иметь прозрачный цвет.

<Button
   android:id="@+id/btnLocation"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="#00000000"
   android:text="@string/menu_location"
   android:paddingRight="7dp"
/>

Ответ 13

Вы можете использовать Библиотека поддержки AppCompat для кнопки Borderless.

Вы можете сделать Borderless Button следующим образом:

<Button
    style="@style/Widget.AppCompat.Button.Borderless"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp" 
    android:text="@string/borderless_button"/>

Вы можете сделать Borderless Colored Button следующим образом:

<Button
    style="@style/Widget.AppCompat.Button.Borderless.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp" 
    android:text="@string/borderless_colored_button"/>

Ответ 14

Таким образом, вы произвольно создаете безграничную (плоскую) кнопку без использования XML

ContextThemeWrapper myContext = new ContextThemeWrapper(this.getActivity(), 
   R.style.Widget_AppCompat_Button_Borderless_Colored);

Button myButton = new Button(myContext, null, 
   R.style.Widget_AppCompat_Button_Borderless_Colored);

Ответ 15

По какой-то причине ни style="Widget.Holo.Button.Borderless", ни android:background="?android:attr/selectableItemBackground" не работали для меня. Точнее, Widget.Holo.Button.Borderless выполнил работу на Android 4.0, но не работал на Android 2.3.3. Что было трюком для меня в обеих версиях: android:background="@drawable/transparent" и этот XML в res/drawable/transparent.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" >
</shape>

Простая прокладка через стену.

Ответ 17

Добавляя к верхнему ответу, вы также можете использовать представления с темно-серым цветом фона в линейном макете, например.

<View
    android:layout_width="match_parent"
    android:layout_height="1dip"
    android:layout_marginBottom="4dip"
    android:layout_marginLeft="4dip"
    android:layout_marginRight="4dip"
    android:layout_marginTop="4dip"
    android:background="@android:color/darker_gray"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dip"
    android:orientation="horizontal"
    android:weightSum="1">

    <Button
        android:id="@+id/button_decline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_weight="0.50"
        android:background="?android:attr/selectableItemBackground"
        android:padding="10dip"
        android:text="@string/decline"/>

    <View
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:layout_marginLeft="4dip"
        android:layout_marginRight="4dip"
        android:background="@android:color/darker_gray"/>

    <Button
        android:id="@+id/button_accept"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_weight="0.50"
        android:background="?android:attr/selectableItemBackground"
        android:padding="10dip"
        android:text="@string/accept"/>
</LinearLayout>

Если ваша линия горизонтальная, вы хотите установить высоту в 1dip и ширину в соответствии с родительским и наоборот, если ваша строка вертикальная.

Ответ 18

Если вы хотите сделать то же самое программно:

(это С#, но он легко переносится на Java)

Button button = new Button(new ContextThemeWrapper(Context, Resource.Style.Widget_AppCompat_Button_Borderless_Colored), null, Resource.Style.Widget_AppCompat_Button_Borderless_Colored);

Match

    <Button
       style="@style/Widget.AppCompat.Button.Borderless.Colored"
    .../>

Ответ 19

Button btn= new Button(this);
btn.setText("HI");
btn.setBackground(null);