Кнопка Android со значком и текстом
У меня есть такие кнопки, как это в моем приложении:
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Search"
android:textSize="24sp" />
Я пытаюсь создать ту же кнопку с текстом и значком.
android: drawableLeft не работает для меня (возможно, это было бы, но я не знаю, как установить максимальную высоту для значка).
Итак, я создал LinearLayout с ImageView и TextView и сделал это как кнопка:
<LinearLayout
android:id="@+id/bSearch2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_default"
android:clickable="true"
android:padding="16dp"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:adjustViewBounds="true"
android:maxHeight="30dp"
android:maxWidth="30dp"
android:scaleType="fitCenter"
android:src="@drawable/search_icon" />
<TextView
android:id="@+id/tvSearchCaption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="24sp"
android:paddingRight="30dp"
android:gravity="center"
android:text="Search" />
</LinearLayout>
Моя новая кнопка - именно то, что я хочу (размер шрифта, значок и размещение текста).
Но это не похоже на мои кнопки по умолчанию:
![enter image description here]()
Итак, я попробовал, чтобы изменить фон и цвет текста моей новой кнопки:
Button Search = (Button) findViewById(R.id.bSearch);
LinearLayout bSearch2 = (LinearLayout) findViewById(R.id.bSearch2);
bSearch2.setBackground(bSearch.getBackground());
TextView tvSearchCaption = (TextView)findViewById(R.id.tvSearchCaption);
tvSearchCaption.setTextColor(bSearch.getTextColors().getDefaultColor());
Это дает странный результат, моя старая кнопка, запуталась:
![enter image description here]()
Когда я изменяю порядок этих двух кнопок в XML, так что сначала появляется "новая кнопка", это делает еще один странный результат:
![enter image description here]()
Теперь я заметил, что когда я пытаюсь нажать старую кнопку, нажимается новая.
Любые идеи?
Ответы
Ответ 1
Попробуйте это.
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Search"
android:drawableLeft="@android:drawable/ic_menu_search"
android:textSize="24sp"/>
Ответ 2
Чтобы добавить изображение влево, вправо, сверху или снизу, вы можете использовать такие атрибуты:
android:drawableLeft
android:drawableRight
android:drawableTop
android:drawableBottom
Пример кода приведен выше. Вы также можете достичь этого с помощью относительной компоновки.
Ответ 3
Для тех, кто хочет сделать это динамически, тогда setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)
на объекте кнопок будет помогать.
Пример
Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);
Ответ 4
@Liem Vo верен, но если вы используете End/Start вместо Right/Left, вам понравится эталонная студия:)
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Search"
android:drawableStart="@android:drawable/ic_menu_search"
android:textSize="24sp"/>
Ответ 5
res/drawable/circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1000dp" />
<solid android:color="#41ba7a" />
<stroke
android:width="2dip"
android:color="#03ae3c" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
разреш/макет/custom_button.xml
<?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"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/circle"
android:drawableTop="@android:drawable/ic_dialog_email"
android:paddingTop="20dp"
android:text="Contact"
android:textColor="#fff" />
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:background="@drawable/circle"
android:drawableTop="@android:drawable/ic_dialog_map"
android:paddingTop="20dp"
android:text="Map"
android:textColor="#fff" />
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:background="@drawable/circle"
android:drawableTop="@android:drawable/ic_dialog_info"
android:paddingTop="20dp"
android:text="Info"
android:textColor="#fff" />
</LinearLayout>
</LinearLayout>
Пример изображения и ссылки ![enter image description here]()
Пример: https://code-android-example.blogspot.com/2019/07/custom-button-with-icon-and-text-in-android.html
Ответ 6
Android: drawableLeft = "@вытяжка/ic_view_list"