android - 如何为此按钮设置点击监听器

标签 android kotlin preferencefragment clicklistener

我无法让它工作 我希望这个 preferences 屏幕上的注销 Button 有一个 ClickListener

它是这样的:

enter image description here

这是代码,buttonView 始终为 NULL:

class PreferencesFragment : PreferenceFragmentCompat() {

    lateinit var activity: Context

    private var prefs: SharedPreferences = BleApplication.getInstance().getDefaultSharedPreferences()

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        activity = requireActivity()
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val buttonView = view.findViewById<View>(R.id.btn_sign_out)

        if (buttonView != null) {
            buttonView.setOnClickListener {
                Toast.makeText(getActivity(), "You clicked me.", Toast.LENGTH_SHORT).show()
            }
        }
        // Hide the divider
/*        setDivider(ColorDrawable(Color.TRANSPARENT))
        setDividerHeight(0)*/
    }

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        addPreferencesFromResource(R.xml.app_prefs)
    }
}

我也试过 kotlinx.android.synthetic 但同样的问题

这是 xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:layout="@layout/pref_category_text"
        android:title="@string/pref_category_remote_battery_title">

        <SwitchPreferenceCompat
            android:key="@string/pref_key_category_remote_battery_switch"
            android:title="@string/pref_category_remote_battery_switch_title"
            android:summary="@string/pref_category_remote_battery_switch_summ"/>

    </PreferenceCategory>

    <PreferenceCategory
        android:layout="@layout/pref_category_text"
        android:title="@string/pref_category_sign_out_title">

        <Preference
            android:key="@string/pref_key_category_signed_out"
            android:widgetLayout="@layout/pref_category_sign_out_button"
            android:title="@string/pref_category_sign_out_button_title"
            android:summary="@string/pref_category_sign_out_buttom_summ"/>

    </PreferenceCategory>

</PreferenceScreen>

这是"@layout/pref_category_sign_out_button"布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_sign_out"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/buttonshape"
        android:text="@string/pref_category_sign_out_title" />
</LinearLayout>

最佳答案

由于您的 Fragment 是从 PreferenceFragmentCompat 扩展的,因此您不应尝试设置 View.OnClickListener,而应覆盖 PreferenceFragmentCompat.onPreferenceTreeClick( ) 代替。根据documentation , 这个方法是...

Called when a preference in the tree rooted at this PreferenceScreen has been clicked.

Java 代码示例:

@Override
onPreferenceTreeClick(Preference preference){
    if(preference.getKey().equals(getContext().getString(R.string.pref_key_category_signed_out))){
       // user clicked signout "button"
       // take appropriate actions
       // return "true" to indicate you handled the click
       return true;
    }
    return false;
}

Kotlin 中的代码示例(我希望我可以信任 Android Studio :P)

override fun onPreferenceTreeClick(preferenceScreen: PreferenceScreen, preference: Preference): Boolean {
    return if (preference.key == context.getString(R.string.pref_key_category_signed_out)) {
        // user clicked signout "button"
        // take appropriate actions
        // return "true" to indicate you handled the click
        true
    } else false
}

这将使您能够捕获 Preference 的点击事件,但不能捕获 Button 的点击事件。

为了同样做到这一点,可以使用自定义 Preference 并覆盖 onBindViewHolder(PreferenceViewHolder)。由于 PreferenceViewHolder - 类似于 RecyclerView.ViewHolder - 有一个包含膨胀布局的字段 itemView,这是一个很好的机会来设置我们自己的 View.OnClickListener

SignOutPreference 扩展自 TwoStatePreference(在 com.android.support:preference-v7 库中),因为替换了 CheckBox 小部件与您的自定义 Button 只需要设置 android:widgetLayout 属性,就像您在代码 fragment 中所做的那样:

<PreferenceCategory
    android:layout="@layout/pref_category_text"
    android:title="@string/pref_category_sign_out_title">

    <your.package.name.SignOutPreference
        android:key="@string/pref_key_category_signed_out"
        android:widgetLayout="@layout/pref_category_sign_out_button"
        android:title="@string/pref_category_sign_out_button_title"
        android:summary="@string/pref_category_sign_out_buttom_summ"/>

</PreferenceCategory>

SignOutPreference.java

public class SignOutPreference extends TwoStatePreference {
    public SignOutPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public SignOutPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

    @Override
    public void onBindViewHolder(final PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);
        Button button = holder.itemView.findViewById(R.id.btn_sign_out);
        if(button != null){
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(holder.itemView.getContext(), "CLICKED!", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

关于android - 如何为此按钮设置点击监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53159360/

相关文章:

kotlin - 如何在 Kotlin 中将数据类转换为 ByteBuffer?

android - Firebase 中有没有一种方法可以自动将 id 列表交换到对象中

android - 在 Android 中获取默认的 Divider

android - 如何在 PreferenceFragment 中使用 DatePickerFragment 获取日期

android - PreferenceFragment 崩溃,空对象引用

android - 更改标题语言 PlacePicker

java - 二进制 XML 文件行 #12 : Error inflating class com. android.phone91.DialPadView

Android Material Button Toggle Group - Check None Selected

java - Android:为什么我不能在新线程中创建处理程序

android - 如何在 Android 的 PreferenceFragment 中添加进度条?