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

Android, как сделать текст кнопки полужирным при нажатии или фокусировке

Я хочу изменить текст внутри кнопки, чтобы быть полужирным, когда кнопка подсвечивается или нажимается. В настоящее время я использую xml файл для определения кнопки и использования XML для изменения способа отображения при нажатии, но я хотел бы сделать это без использования изображения.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true"
          android:state_pressed="false" 
          android:drawable="@drawable/reset_hover" />
    <item android:state_focused="true" 
          android:state_pressed="true"
          android:drawable="@drawable/reset_hover" />
    <item android:state_focused="false" 
          android:state_pressed="true"
      android:drawable="@drawable/reset_hover" />
    <item android:drawable="@drawable/reset" />
</selector>

Я попытался использовать что-то вроде следующего, но он, кажется, никогда не вызван.

    final Button btn_reset = (Button) findViewById(R.id.btn_reset);
    btn_reset.setOnClickListener(this); 
    btn_reset.setOn(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus){btn_reset.setTypeface(null, Typeface.BOLD);}
        else{btn_reset.setTypeface(null, Typeface.NORMAL);}
    }
   });
4b9b3361

Ответ 1

Вы можете создать свой собственный style.xml, в котором вы определяете стиль текста. В вашем селекторе вы можете ссылаться на стиль. style.xml

<style name="myStyle">  
    <item name="android:textSize">9px</item>
    <item name="android:gravity">center_horizontal</item>
    <item name="android:textColor">#fff</item>
    <item name="android:textStyle">bold</item>
</style>

И в вашем селекторе

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
      android:state_pressed="false" 
      style="@style/myStyle" /> </selector>

Ответ 2

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

final Button button = (Button) findViewById(R.id.button_id);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Set bold on click
                 button.setTypeface(null, Typeface.BOLD);
             }
         });

Ответ 3

Стили не допускаются в селекторах. Ссылка


И чтобы сделать текст полужирным, используйте этот код:

btn_reset.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            // When the user clicks the Button
            case MotionEvent.ACTION_DOWN:
                btn_reset.setTypeface(Typeface.DEFAULT_BOLD);
                break;

            // When the user releases the Button
            case MotionEvent.ACTION_UP:
                btn_reset.setTypeface(Typeface.DEFAULT);
                break;
        }
        return false;
    }
});

Ответ 4

Пользовательские виды - наше спасение :) Вот пользовательская кнопка, которую вы можете использовать для этого.

class PressedButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    @AttrRes defStyleAttr: Int = 0
) : Button(context, attrs, defStyleAttr) {

    @FontRes val defaultPressedFontId = Typeface.DEFAULT_BOLD
    @FontRes val defaultNormalFontId = Typeface.DEFAULT

    @FontRes var pressedFontId = defaultPressedFontId
    @FontRes var normalFontId = defaultNormalFontId

    init {
        attrs?.let { initAttrs(context, it) }

        setOnTouchListener { _, event ->
            [email protected] when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    typeface = getFont(context, pressedFontId)
                    true
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    typeface = getFont(context, normalFontId)
                    true
                }
                else -> false
            }
        }
    }

    private fun initAttrs(context: Context, attrs: AttributeSet) {
        val a = context.obtainStyledAttributes(attrs, R.styleable.PressedButton, 0, 0)
        pressedFontId = a.getResourceId(R.styleable.PressedButton_font_style_pressed, defaultPressedFontId)
        normalFontId = a.getResourceId(R.styleable.PressedButton_font_style_normal, defaultNormalFontId)
        a.recycle()
    }
}

стиль:

<declare-styleable name="PressedButton">
    <attr name="font_style_pressed" format="reference" />
    <attr name="font_style_normal" format="reference" />
</declare-styleable>

а вот метод getFont

public static Typeface getFont(Context context, int typefaceResourceId) {
    Typeface typeface = null;
    if (typefaceResourceId != 0) {
        typeface = ResourcesCompat.getFont(context, typefaceResourceId);
    }
    if (typeface != null) {
        return typeface;
    } else {
        return ResourcesCompat.getFont(context, FONT_DEFAULT);
    }
}