Мне нужно добавить стрелку к следующей кнопке вот так
Как проще всего этого добиться? Создание пользовательского составного представления звучит как излишество
PS Символ > нехороший.
Просто используйте TextView.
<TextView
android:id = "@+id/some_id"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/next"
android:drawableRight = "@drawable/arrow_right"
android:clickable = "true"
android:focusable = "true"
android:background = "?android:selectableItemBackground"
/>
TextViews поддерживают составные чертежи, где вы можете указать объект, который вы хотите отображать рядом с текстом. Это может быть сверху, снизу, справа, слева, начало, конец.
Также обратите внимание, что я сделал TextView доступным для кликов и фокусировкой, и что я дал ему фон пульсации Android по умолчанию (где он показывает эффект пульсации при нажатии).
РЕДАКТИРОВАТЬ
Если вам нужно, чтобы стрелка была сразу после текста, вы должны использовать контейнер и дочерние представления:
<LinearLayout
android:id = "@+id/button_wrapper"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center"
android:clickable = "true"
android:focusable = "true"
android:background = "?android:selectableItemBackground">
<TextView
android:id = "@+id/some_textview"
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:text = "@string/next" />
<ImageView
android:id = "@+id/some_image"
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:src = "@drawable/arrow_right" />
</LinearLayout>
Вам нужно установить прослушиватель кликов на LinearLayout.
В качестве альтернативы используйте символ U + 276fa как часть текста TextView: ❯. Это не > и больше похоже на стрелку.
Затем вам нужно сделать свой макет. Я отредактирую на примере.
как я уже упоминал в этой теме, я хотел избежать создания составных представлений, но благодаря вам я знаю, что это, вероятно, невозможно. Кстати, Юникод слишком мал
Вместо этого попробуйте U + 276f.
На этот раз базовая линия не выровнена. В любом случае спасибо, я буду придерживаться пользовательского просмотра
Попробуйте эту настраиваемую кнопку, она вычисляет, где поместить значок непосредственно рядом с текстом.
public class CenteredIconButton extends Button {
private static final int LEFT = 0, TOP = 1, RIGHT = 2, BOTTOM = 3;
private Rect textBounds = new Rect();
private Rect drawableBounds = new Rect();
public CenteredIconButton(Context context) {
this(context, null);
}
public CenteredIconButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.buttonStyle);
}
public CenteredIconButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (!changed) return;
final CharSequence text = getText();
if (!TextUtils.isEmpty(text)) {
TextPaint textPaint = getPaint();
textPaint.getTextBounds(text.toString(), 0, text.length(), textBounds);
} else {
textBounds.setEmpty();
}
final int width = getWidth() - (getPaddingLeft() + getPaddingRight());
final int height = getHeight() - (getPaddingTop() + getPaddingBottom());
final Drawable[] drawables = getCompoundDrawables();
if (drawables[LEFT] != null) {
drawables[LEFT].copyBounds(drawableBounds);
int leftOffset =
(width - (textBounds.width() + drawableBounds.width()) + getRightPaddingOffset()) / 2 - getCompoundDrawablePadding();
drawableBounds.offset(leftOffset, 0);
drawables[LEFT].setBounds(drawableBounds);
}
if (drawables[RIGHT] != null) {
drawables[RIGHT].copyBounds(drawableBounds);
int rightOffset =
((textBounds.width() + drawableBounds.width()) - width + getLeftPaddingOffset()) / 2 + getCompoundDrawablePadding();
drawableBounds.offset(rightOffset, 0);
drawables[RIGHT].setBounds(drawableBounds);
}
if (drawables[TOP] != null) {
drawables[TOP].copyBounds(drawableBounds);
int topOffset =
(height - (textBounds.height() + drawableBounds.height()) + getBottomPaddingOffset()) / 2 - getCompoundDrawablePadding();
drawableBounds.offset(topOffset, 0);
drawables[TOP].setBounds(drawableBounds);
}
}
}
С этим есть одна проблема. Если у меня кнопка
android:layout_width = "match_parent", иконка будет у правого края, а не рядом с меткой.