Jak wyśrodkować ikonę i tekst w przycisku Androida z szerokością ustawioną na „wypełnij rodzica”


Chcę mieć przycisk Androida z ikoną + tekst w środku. Używam atrybutu drawableLeft, aby ustawić obraz, działa to dobrze, jeśli przycisk ma szerokość
"wrap_content"
, ale muszę rozciągnąć do maksymalnej szerokości, więc używam
"fill_parent"  szerokość. Spowoduje to przeniesienie mojej ikony bezpośrednio na lewo od przycisku i chcę, aby zarówno ikona, jak i tekst były wyśrodkowane wewnątrz przycisku. 
Próbowałem dostosować dopełnienie, ale to pozwala na podanie tylko stałej wartości, więc nie tego potrzebuję. Potrzebuję wyśrodkowania ikony + tekstu.
<Button 
android:id="@+id/startTelemoteButton"
android:text="@string/start_telemote"
android:drawableLeft="@drawable/start"
android:paddingLeft="20dip"
android:paddingRight="20dip"
android:width="fill_parent"
android:heigh="wrap_content"/>

Jakieś sugestie, jak mogę to osiągnąć?
Zaproszony:
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

android: drawableLeft zawsze utrzymuje android: paddingLeft z dala od lewej krawędzi. Gdy przycisk nie jest ustawiony na android: width = "wrap_content", zawsze zawiesza się po lewej stronie!
W przypadku atrybutu systemu Android 4.0 (poziom interfejsu API 14) można użyć atrybutu android: drawableStart, aby umieścić rysunek na początku tekstu. Jedynym rozwiązaniem kompatybilnym wstecz, które wymyśliłem, jest użycie

ImageSpan
http://developer.android.com/r ... .html
aby utworzyć tekst + obraz objęty:
Button button = (Button) findViewById(R.id.button);
Spannable buttonLabel = new SpannableString(" Button Text");
buttonLabel.setSpan(new ImageSpan(getApplicationContext(), R.drawable.icon,
ImageSpan.ALIGN_BOTTOM), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(buttonLabel);

W moim przypadku musiałem również dostosować atrybut android: gravity Button, aby wyglądał na wyśrodkowany:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="32dp"
android:minWidth="150dp"
android:gravity="center_horizontal|top"/>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Wiem, że spóźniłem się z odpowiedzią na to pytanie, ale to mi pomogło:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="10dp"
android:background="@color/fb" > <Button
android:id="@+id/fbLogin"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@null"
android:drawableLeft="@drawable/ic_facebook"
android:gravity="center"
android:minHeight="0dp"
android:minWidth="0dp"
android:text="FACEBOOK"
android:textColor="@android:color/white"/>
</FrameLayout>

Znalazłem to rozwiązanie stąd:

Problem z interfejsem użytkownika Androida: tworzenie przycisku z wyśrodkowanym tekstem i ikoną
http://porcupineprogrammer.blo ... .html
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:


Wszystkie poprzednie odpowiedzi wydają się być nieaktualne

Teraz możesz użyć
MaterialButton
, który pozwala ustawić wagę ikony.
<com.google.android.material.button.MaterialButton
android:id="@+id/btnDownloadPdf"
android:layout_width="0dp"
android:layout_height="56dp"
android:layout_margin="16dp"
android:gravity="center"
android:textAllCaps="true"
app:backgroundTint="#fc0"
app:icon="@drawable/ic_pdf"
app:iconGravity="textStart"
app:iconPadding="10dp"
app:iconTint="#f00"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:text="Download Pdf"/>

https://i.stack.imgur.com/jX67S.png
Aby użyć komponentów materiałowych, potrzebujesz oczywiście:
Dodaj zależność
implementacja „com.google.android.material: material: 1.3.0-alpha01”
(użyj najnowszej wersji)
Ustaw swój motyw jako rozszerzony motyw komponentów materiałowych
<style name="AppTheme" parent="Theme.MaterialComponents.Light">...
</style>

Jeśli nie możesz tego zrobić, rozszerz go z motywu Material Bridge
<style name="AppTheme" parent="Theme.MaterialComponents.Light.Bridge">...
</style>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

użyłem

LinearLayout

zamiast

Button

. OnClickListener
którego muszę użyć, działa również świetnie dla LinearLayout.
<LinearLayout
android:id="@+id/my_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector"
android:gravity="center"
android:orientation="horizontal"
android:clickable="true"> <ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/icon"/> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Text"/></LinearLayout>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Dostosowuję go, dodając lewą i prawą wyściółkę w następujący sposób:
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/btn_facebookact_like"
android:text="@string/btn_facebookact_like"
android:textColor="@color/black"
android:textAllCaps="false"
android:background="@color/white"
android:drawableStart="@drawable/like"
android:drawableLeft="@drawable/like"
android:gravity="center"
android:layout_gravity="center"
android:paddingLeft="40dp"
android:paddingRight="40dp"
/>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Niedawno stanąłem przed tym samym problemem. Próbowałem znaleźć tańsze rozwiązanie, więc wymyśliłem to.
<LinearLayout
android:id="@+id/linearButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/selector_button_translucent_ab_color"
android:clickable="true"
android:descendantFocusability="blocksDescendants"
android:gravity="center"
android:orientation="horizontal" > <ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher"/> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textColor="@android:color/white"/>
</LinearLayout>

Następnie po prostu zadzwoń do
OnClickListener
na
LinearLayout
.
Mam nadzieję, że to komuś pomoże, ponieważ wydaje się, że jest to bardzo powszechny problem. :)
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Możesz użyć niestandardowego przycisku, który sam mierzy i rysuje, aby umieścić lewy rysunek. Proszę znaleźć przykład i zastosowanie

tutaj
https://gist.github.com/rajivnarayana/5224881
public class DrawableAlignedButton extends Button { public DrawableAlignedButton(Context context, AttributeSet attrs) {
super(context, attrs);
}public DrawableAlignedButton(Context context) {
super(context);
}public DrawableAlignedButton(Context context, AttributeSet attrs, int style) {
super(context, attrs, style);
}private Drawable mLeftDrawable;@Override
//Overriden to work only with a left drawable.
public void setCompoundDrawablesWithIntrinsicBounds(Drawable left,
Drawable top, Drawable right, Drawable bottom) {
if(left == null) return;
left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
mLeftDrawable = left;
}@Override
protected void onDraw(Canvas canvas) {
//transform the canvas so we can draw both image and text at center.
canvas.save();
canvas.translate(2+mLeftDrawable.getIntrinsicWidth()/2, 0);
super.onDraw(canvas);
canvas.restore();
canvas.save();
int widthOfText = (int)getPaint().measureText(getText().toString());
int left = (getWidth()+widthOfText)/2 - mLeftDrawable.getIntrinsicWidth() - 2;
canvas.translate(left, (getHeight()-mLeftDrawable.getIntrinsicHeight())/2);
mLeftDrawable.draw(canvas);
canvas.restore();
}@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = getMeasuredHeight();
height = Math.max(height, mLeftDrawable.getIntrinsicHeight() + getPaddingTop() + getPaddingBottom());
setMeasuredDimension(getMeasuredWidth(), height);
}
}

Za pomocą
<com.mypackage.DrawableAlignedButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableLeft="@drawable/my_drawable"
android:gravity="center"
android:padding="7dp"
android:text="My Text"/>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

To jest moje rozwiązanie, które napisałem 3 lata temu. Przycisk ma tekst i lewą ikonę i znajduje się w ramce, która jest tutaj rzeczywistym przyciskiem i można go rozciągnąć za pomocą fill_parent. Nie mogę tego ponownie przetestować, ale wtedy zadziałało. Button prawdopodobnie nie musi być używany i można go zastąpić TextView, ale nie będę go teraz testować i nie zmienia tu zbytnio funkcjonalności.
<FrameLayout
android:id="@+id/login_button_login"
android:background="@drawable/apptheme_btn_default_holo_dark"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:layout_height="40dp">
<Button
android:clickable="false"
android:drawablePadding="15dp"
android:layout_gravity="center"
style="@style/WhiteText.Small.Bold"
android:drawableLeft="@drawable/lock"
android:background="@color/transparent"
android:text="LOGIN"/>
</FrameLayout>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Wiem, że to pytanie jest nieco starsze, ale być może nadal jesteś otwarty na wskazówki lub obejścia:
Utwórz RelativeLayout „wrap_content” z obrazem przycisku jako tłem lub samym przyciskiem jako pierwszym elementem układu. Weź LinearLayout i ustaw go na „layout_centerInParent” i „wrap_content”. Następnie ustaw swój Drawable na Imageview. Na koniec zainstaluj TextView z tekstem (ustawienia regionalne).
więc w zasadzie masz taką strukturę:
RelativeLayout
Button
LinearLayout
ImageView
TextView

lub tak:
RelativeLayout with "android-specific" button image as background
LinearLayout
ImageView
TextView

Wiem, że jest wiele elementów, z którymi można sobie poradzić w tym rozwiązaniu, ale bardzo łatwo można za jego pomocą stworzyć własny niestandardowy przycisk, a także ustawić dokładne położenie tekstu i rysunków :)
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Moim sposobem rozwiązania tego problemu było otoczenie przycisku jasnymi elementami
& < View ../>
, które dynamicznie zmieniają rozmiar. Poniżej znajduje się kilka przykładów tego, co możesz dzięki temu osiągnąć:
https://i.stack.imgur.com/vGIdF.png
Zauważ, że klikalny obszar przycisków w Przykładzie 3 jest taki sam jak w Przykładzie 2 (tj. Ze spacjami), który różni się od Przykładu 4, gdzie nie ma między nimi "niemożliwych do kliknięcia" przerw.
Kod:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[url=http://schemas.android.com/apk/res/android"]http://schemas.android.com/apk/res/android"[/url]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Example 1: Button with a background color:"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="20dp"
android:paddingEnd="20dp"
android:layout_weight="0.3"/>
<!-- Play around with the above 3 values to modify the clickable
area and image alignment with respect to text -->
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout> <TextView
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Example 2: Button group + transparent layout + spacers:"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout> <TextView
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Example 3: Button group + colored layout:"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray">
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout> <TextView
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Example 4 (reference): Button group + no spacers:"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray">
<Button
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
<Button
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
<Button
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:drawableLeft="@android:drawable/ic_secure"
android:drawableStart="@android:drawable/ic_secure"
android:background="@android:color/darker_gray"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Możesz stworzyć swój własny widget:

Klasa IButton w języku Java

:
public class IButton extends RelativeLayout {private RelativeLayout layout;
private ImageView image;
private TextView text;public IButton(Context context) {
this(context, null);
}public IButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}public IButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.ibutton, this, true); layout = (RelativeLayout) view.findViewById(R.id.btn_layout); image = (ImageView) view.findViewById(R.id.btn_icon);
text = (TextView) view.findViewById(R.id.btn_text); if (attrs != null) {
TypedArray attributes = context.obtainStyledAttributes(attrs,R.styleable.IButtonStyle); Drawable drawable = attributes.getDrawable(R.styleable.IButtonStyle_button_icon);
if(drawable != null) {
image.setImageDrawable(drawable);
} String str = attributes.getString(R.styleable.IButtonStyle_button_text);
text.setText(str); attributes.recycle();
}}@Override
public void setOnClickListener(final OnClickListener l) {
super.setOnClickListener(l);
layout.setOnClickListener(l);
}public void setDrawable(int resId) {
image.setImageResource(resId);
}

}

Układ ibutton.xml

<RelativeLayout xmlns:android="[url=http://schemas.android.com/apk/res/android"]http://schemas.android.com/apk/res/android"[/url]
android:id="@+id/btn_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" ><ImageView
android:id="@+id/btn_icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="2dp"
android:layout_toLeftOf="@+id/btn_text"
android:duplicateParentState="true"/><TextView
android:id="@+id/btn_text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:duplicateParentState="true"
android:gravity="center_vertical"
android:textColor="#000000"/>
</RelativeLayout>


Aby użyć tego niestandardowego widżetu

:
<com.test.android.widgets.IButton
android:id="@+id/new"
android:layout_width="fill_parent"
android:layout_height="@dimen/button_height"
ibutton:button_text="@string/btn_new"
ibutton:button_icon="@drawable/ic_action_new"/>


Musisz podać przestrzeń nazw dla atrybutów niestandardowych

xmlns:ibutton="http://schemas.android.com/apk ... ot%3B
gdzie com.test.android.xxx to główny pakiet aplikacji.
Po prostu umieść to pod xmlns: android = "http://schemas.android.com/apk/res/android&quot;.
Ostatnią rzeczą, której potrzebujesz, są atrybuty niestandardowe w attrs.xml.

W latach 40

<?xml version="1.0" encoding="utf-8"?>
<resources> <declare-styleable name="IButtonStyle">
<attr name="button_text"/>
<attr name="button_icon" format="integer"/>
</declare-styleable> <attr name="button_text"/></resources>

Aby uzyskać lepsze pozycjonowanie, zawiń niestandardowy Button wewnątrz LinearLayout, jeśli chcesz uniknąć potencjalnych problemów z pozycjonowaniem w RelativeLayout.
Cieszyć się!
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Miałem podobny problem, ale chciałem mieć centrum rysowania bez tekstu i bez zawiniętych układów. Rozwiązaniem było stworzenie niestandardowego przycisku i dodanie kolejnego elementu do rysowania oprócz LEFT, RIGHT, TOP, BOTTOM. Możesz łatwo zmienić położenie rysunku i ustawić go w żądanym położeniu względem tekstu.
CenterDrawableButton.java
public class CenterDrawableButton extends Button {
private Drawable mDrawableCenter; public CenterDrawableButton(Context context) {
super(context);
init(context, null);
} public CenterDrawableButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
} public CenterDrawableButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
} @TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CenterDrawableButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs){
//if (isInEditMode()) return;
if(attrs!=null){
TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.CenterDrawableButton, 0, 0); try {
setCenterDrawable(a.getDrawable(R.styleable.CenterDrawableButton_drawableCenter)); } finally {
a.recycle();
} }
} public void setCenterDrawable(int center) {
if(center==0){
setCenterDrawable(null);
}else
setCenterDrawable(getContext().getResources().getDrawable(center));
}
public void setCenterDrawable(@Nullable Drawable center) {
int[] state;
state = getDrawableState();
if (center != null) {
center.setState(state);
center.setBounds(0, 0, center.getIntrinsicWidth(), center.getIntrinsicHeight());
center.setCallback(this);
}
mDrawableCenter = center;
invalidate();
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if(mDrawableCenter!=null) {
setMeasuredDimension(Math.max(getMeasuredWidth(), mDrawableCenter.getIntrinsicWidth()),
Math.max(getMeasuredHeight(), mDrawableCenter.getIntrinsicHeight()));
}
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mDrawableCenter != null) {
int[] state = getDrawableState();
mDrawableCenter.setState(state);
mDrawableCenter.setBounds(0, 0, mDrawableCenter.getIntrinsicWidth(),
mDrawableCenter.getIntrinsicHeight());
}
invalidate();
} @Override
protected void onDraw(@NonNull Canvas canvas) {
super.onDraw(canvas); if (mDrawableCenter != null) {
Rect rect = mDrawableCenter.getBounds();
canvas.save();
canvas.translate(getWidth()/2 - rect.right/2, getHeight()/2 - rect.bottom/2);
mDrawableCenter.draw(canvas);
canvas.restore();
}
}
}

attrs.xml
<resources>
<attr name="drawableCenter" format="reference"/>
<declare-styleable name="CenterDrawableButton">
<attr name="drawableCenter"/>
</declare-styleable>
</resources>

za pomocą
<com.virtoos.android.view.custom.CenterDrawableButton
android:id="@id/centerDrawableButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:drawableCenter="@android:drawable/ic_menu_info_details"/>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

<style name="captionOnly">
<item name="android:background">@null</item>
<item name="android:clickable">false</item>
<item name="android:focusable">false</item>
<item name="android:minHeight">0dp</item>
<item name="android:minWidth">0dp</item>
</style><FrameLayout
style="?android:attr/buttonStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content" > <Button
style="@style/captionOnly"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableLeft="@android:drawable/ic_delete"
android:gravity="center"
android:text="Button Challenge"/>
</FrameLayout>

Umieść FrameLayout w LinearLayout i ustaw orientację poziomą.
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Możesz umieścić przycisk na górze LinearLayout
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="@dimen/activity_login_fb_height"
android:background="@mipmap/bg_btn_fb">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lblLoginFb"
android:textColor="@color/white"
android:drawableLeft="@mipmap/icon_fb"
android:textSize="@dimen/activity_login_fb_textSize"
android:text="Login with Facebook"
android:gravity="center"/>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/btnLoginFb"
android:background="@color/transparent"
/>
</RelativeLayout>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Co się stanie, jeśli wypróbujesz android: gravity = "center_horizontal"?
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Jak zasugerował Rodya, przed wersją 4.0 nie było bezpośredniego sposobu na wyśrodkowanie tekstu za pomocą rysunków. Rzeczywiście, ustawienie padding_left rzeczywiście powoduje odsunięcie elementu rysunkowego od granicy. Sugeruję więc, aby w czasie wykonywania dokładnie obliczyć, ile pikseli od lewej krawędzi powinien mieć rysunek, a następnie przekazać go za pomocą

setPadding
http://developer.android.com/r ... 28int,%20int,%20int,%20int%29
.
int paddingLeft = (button.getWidth() - drawableWidth - textWidth)/2;

Szerokość rysunku jest stała i możesz go wyświetlić i obliczyć lub zgadnąć szerokość tekstu.
Na koniec będziesz musiał pomnożyć wartość wypełnienia przez gęstość ekranu, co możesz zrobić

DisplayMetrics
http://developer.android.com/r ... .html
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Myślę, że android: gravity = "center" powinien działać
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Nie testuję tego, ale wygląda na to, że możesz użyć

biblioteka
https://github.com/steelkiwi/CenteredContentButton
CenteredContentButton
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

public class DrawableCenterTextView rozszerza TextView {
public DrawableCenterTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}public DrawableCenterTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}public DrawableCenterTextView(Context context) {
super(context);
}@Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (drawables != null) {
Drawable drawableLeft = drawables[0];
Drawable drawableRight = drawables[2];
if (drawableLeft != null || drawableRight != null) {
float textWidth = getPaint().measureText(getText().toString());
int drawablePadding = getCompoundDrawablePadding();
int drawableWidth = 0;
if (drawableLeft != null)
drawableWidth = drawableLeft.getIntrinsicWidth();
else if (drawableRight != null) {
drawableWidth = drawableRight.getIntrinsicWidth();
}
float bodyWidth = textWidth + drawableWidth + drawablePadding;
canvas.translate((getWidth() - bodyWidth)/2, 0);
}
}
super.onDraw(canvas);
}

}
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Brudny interes.
android:paddingTop="10dp"
android:drawableTop="@drawable/ic_src"

Obliczenie prawidłowego wypełnienia rozwiązuje ten cel. Jednak w przypadku zróżnicowanego ekranu użyj innego odstępnika i umieść tę wartość w Interesource w odpowiednim folderze.
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Posługiwać się

RelativeLayout

(pojemnik) i

android:layout_centerHorizontal="true"

moja próbka:
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" > <CheckBox
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:button="@drawable/bg_fav_detail"
android:drawablePadding="5dp"
android:text=" Favorite"/>
</RelativeLayout>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Inną opcją jest zachowanie motywu przycisku.
<Button
android:id="@+id/pf_bt_edit"
android:layout_height="@dimen/standard_height"
android:layout_width="match_parent"
/> <LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignBottom="@id/pf_bt_edit"
android:layout_alignLeft="@id/pf_bt_edit"
android:layout_alignRight="@id/pf_bt_edit"
android:layout_alignTop="@id/pf_bt_edit"
android:layout_margin="@dimen/margin_10"
android:clickable="false"
android:elevation="20dp"
android:gravity="center"
android:orientation="horizontal"
> <ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:clickable="false"
android:src="@drawable/ic_edit_white_48dp"/> <TextView
android:id="@+id/pf_tv_edit"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="@dimen/margin_5"
android:clickable="false"
android:gravity="center"
android:text="@string/pf_bt_edit"/> </LinearLayout>

Dzięki temu rozwiązaniu, jeśli Twój add
@color/your_color
@color/your_highlight_color
w swoim motywie działania możesz mieć motyw materiału na lizaku z cieniem i falowaniem, a dla poprzedniej wersji płaski przycisk z Twoim kolorem i podświetleniem koloru po kliknięciu.
Co więcej, przy pomocy tego rozwiązania obraz jest autorezowany
Wynik:
Najpierw na urządzeniach Lollipop
Po drugie: na urządzeniach typu pre-Lollipop
3: przycisk urządzenia pre-lollipop
https://i.stack.imgur.com/eufDz.png
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Wyśrodkowałem
textView
z ikoną
paddingLeft
i wyrównanym textView

left | centerVertical

a dla małej przerwy między widokiem a ikoną użyłem
drawablePadding
<Button
android:id="@+id/have_it_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/textbox"
android:drawableLeft="@drawable/have_it"
android:drawablePadding="30dp"
android:gravity="left|center_vertical"
android:paddingLeft="60dp"
android:text="Owner Contact"
android:textColor="@android:color/white"/>
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

To może być stary/zamknięty temat, ale szukałem wszędzie i nie znalazłem nic przydatnego, dopóki nie zdecydowałem się stworzyć własnego rozwiązania. Jeśli ktoś szuka tutaj odpowiedzi, wypróbuj tę, może zaoszczędzi Ci to minuty na zastanowienie.
<LinearLayout
android:id="@+id/llContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/selector"
android:clickable="true"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:textStyle="bold"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="This is a text"/> <ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_image/>
</LinearLayout>

Ponieważ układ linii działa jak kontener, a ten z selektorem po kliknięciu całego układu linii będzie wyglądał dokładnie tak, jak powinien. jeśli chcesz, aby był wyśrodkowany w tym samym czasie, użyj względnej instancji. Jeśli chcesz, aby był wyśrodkowany w poziomie, zmień orientację na poziomą.
Uwaga,

co nie

zapomnij dodać

android:clickable="true"

do głównego pojemnika (względnego lub liniowego), aby akcja miała miejsce.
Ponownie, może to być stary wątek, ale nadal może komuś pomóc.
- hura, mam nadzieję, że to pomoże -
szczęśliwe kodowanie.

Aby odpowiedzieć na pytania, Zaloguj się lub Zarejestruj się