AndroidX中的自定义ListPreference
创始人
2024-10-12 19:30:36
0

在AndroidX中,可以通过继承Preference类来创建自定义的ListPreference。下面是一个示例代码:

首先,在build.gradle文件中添加以下依赖项:

implementation 'androidx.preference:preference:1.1.1'

接下来,创建一个CustomListPreference类,继承自ListPreference:

import android.content.Context;
import android.util.AttributeSet;
import androidx.preference.ListPreference;

public class CustomListPreference extends ListPreference {

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

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

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);

        // 在列表项被选择后的回调方法
        if (positiveResult) {
            // 获取选中的值
            String selectedValue = getValue();

            // 在这里可以根据选中的值进行相应的处理
        }
    }
}

在XML布局文件中使用CustomListPreference:



    


请注意,@array/preferences_options@array/preferences_values是在res/values/arrays.xml文件中定义的字符串数组,用于提供选项列表和对应的值。

最后,在相关的Activity或Fragment中加载该设置页面:

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceFragmentCompat;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings_container, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.preferences, rootKey);
        }
    }
}

这样就可以在AndroidX中使用自定义的ListPreference了。

相关内容

热门资讯

于此同时!pokemmo手机辅... 于此同时!pokemmo手机辅助软件,微乐南昌辅助神器,讲义教程(有挂解密)微乐南昌辅助神器脚本下载...
现就发布提示!wepoker智... 现就发布提示!wepoker智能辅助插件,来趣广西友玩脚本辅助,窍门教程(有挂透明挂)来趣广西友玩脚...
攻略辅助挂!wepoker俱乐... 攻略辅助挂!wepoker俱乐部辅助器,传送屋软件下载辅助,妙招教程(有挂讲解)1、游戏颠覆性的策略...
黑科技技巧!wejoker辅助... 黑科技技巧!wejoker辅助器要钱玩吗,潮汕雀友会辅助,积累教程(有挂辅助)1、很好的工具软件,可...
插件辅助挂!拱趴大菠萝有挂吗,... 插件辅助挂!拱趴大菠萝有挂吗,边锋老友荣成辅助器,方式教程(有人有挂)1、边锋老友荣成辅助器破解器简...
网友热议!红龙poker辅助,... 网友热议!红龙poker辅助,hhpoker这个软件靠谱吗,方案教程(揭秘有挂)1、超多福利:超高返...
经调查!aapoker真的假的... 经调查!aapoker真的假的,赣湘互娱怎么下载辅助,演示教程(有挂规律)1、经调查!aapoker...
2026版攻略!有没有人wep... 2026版攻略!有没有人wepoker,山城九九辅助,手段教程(有挂功能)1、下载好山城九九辅助脚本...
2026版规律!wepoker... 2026版规律!wepoker私人局透视插件,楚天游辅助,操作教程(有挂规律)1、实时楚天游辅助透视...
黑科技插件!菠萝辅助器免费版的... 黑科技插件!菠萝辅助器免费版的特点,多乐游戏修改器,办法教程(讲解有挂)1、多乐游戏修改器脚本辅助下...