我是Kotlin的新手,我有一个简单的PreferencesFragment
,它具有用于按钮的自定义布局xml。该按钮在Preferences
项目中显示为ok。现在,我想在按钮上放置这个setOnClickListener
,但是下面的buttonView
为NULL。我想念什么。我认为findViewById
这是@ 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>
我的app_prefs
<?xml version="1.0" encoding="utf-8"?>
<preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<preference.PreferenceCategory
android:layout="@layout/pref_category_text"
android:title="@string/pref_category_sign_out_title">
<preference.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"/>
</preference.PreferenceCategory>
</preference.PreferenceScreen>
我的PreferenceFragmentCompat:
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 onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.app_prefs)
val buttonView = view.findViewById<Button>(R.id.btn_sign_out)
if (buttonView != null) {
buttonView.setOnClickListener {
Toast.makeText(getActivity(), "You clicked me.", Toast.LENGTH_SHORT).show()
}
}
}