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了。

相关内容

热门资讯

透视玄学"werpl... 透视玄学"werplan外挂"详细辅助揭秘攻略(透视app下载透视)1、不需要AI权限,帮助你快速的...
透视好友"佛手大菠萝... 1、透视好友"佛手大菠萝辅助"详细辅助教你攻略(手机版透视脚本技巧)2、进入游戏-大厅左侧-新手福利...
透视安装"德州辅助工... 1、透视安装"德州辅助工具到底怎么样"详细辅助大神讲解(免费钻石方法)2、进入游戏-大厅左侧-新手福...
透视透视"pokem... 透视透视"pokemmo辅助器脚本下载"详细辅助切实教程(网页版透视方法教程);1分钟了解详细教程(...
透视计算"wepok... 透视计算"wepoker有辅助工具吗"详细辅助教你攻略(外挂辅助);1分钟了解详细教程(微信 136...
透视黑科技"wepo... 透视黑科技"wepoker可以透视码"详细辅助技巧教程(可以开透视技巧);亲真的是有正版授权,小编(...
透视游戏"wepok... 1、透视游戏"wepoker黑侠辅助器"详细辅助玩家教你(辅助软件价格攻略);详细教程。2、wepo...
透视挂透视"aa p... 透视挂透视"aa poker辅助包"详细辅助透明挂教程(究竟有透视神器);建议优先通过aa poke...
透视有挂"来玩app... 透视有挂"来玩app破解版"详细辅助2025教程(内置辅助透视)科技教程也叫必备教程,这是一款功能强...
透视能赢"wepok... 透视能赢"wepoker免费脚本弱密码"详细辅助我来教教你(插件程序激活码攻略);科技安装教程;13...