简体   繁体   English

偏好片段中的按钮

[英]Button in Preference Fragment

I need to add a button into a Preference Fragment Layout.我需要在偏好片段布局中添加一个按钮。 I can succesfully get the button in the Preferences layout, but I cannot capture the event of it being clicked.我可以成功获取首选项布局中的按钮,但我无法捕获它被单击的事件。

all other preferences are captured in the onSharedPreferenceChanged Callback, but the button click is not.所有其他首选项都在 onSharedPreferenceChanged 回调中捕获,但按钮单击不是。

What is the best way to add a callback to the button, or have it return it's value in the onSharedPreferenceChanged callback?向按钮添加回调或让它在 onSharedPreferenceChanged 回调中返回其值的最佳方法是什么?

I've tried almost all examples I could find on Stackoverflow, but most are designed with a preferenceActivity in mind, not a fragment.我已经尝试了几乎所有可以在 Stackoverflow 上找到的示例,但大多数都是在设计时考虑到了偏好活动,而不是片段。

One solution I tried did fire a callback event, but only when that callback was in the host Activity!我尝试过的一种解决方案确实触发了回调事件,但仅当该回调位于主机 Activity 中时!

Fragment specific help on this appreciated.对此片段的具体帮助表示赞赏。

This should work in your fragment: 这应该在您的片段中起作用:

    Button prefBtn = ((Button) view.findViewById(R.id.prefBtn));
    prefBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            // Your code here
        }
    });

EDIT 编辑
You also need something like this in your fragment layout: 您还需要在片段布局中添加以下内容:

    <Button
        android:id="@+id/prefBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

For the whole item click:对于整个项目,请单击:

preferenceManager.findPreference<Preference>("your_key")?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
    Timber.d("click item")
    return@OnPreferenceClickListener false
}

For only the button: u need a custom preference.仅对于按钮:您需要自定义首选项。

class FooterPreference(context: Context, attrs: AttributeSet): Preference(context, attrs) {

    override fun onBindViewHolder(holder: PreferenceViewHolder?) {
        super.onBindViewHolder(holder)
        holder?.itemView?.findViewById<Button>(R.id.btn)?.setOnClickListener {
            Timber.d("click btn")
        }
    }
}
<packageName.FooterPreference
        app:layout="@layout/layout_preference_footer" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM