其他分享
首页 > 其他分享> > android – 如何在PreferenceScreen中添加按钮?

android – 如何在PreferenceScreen中添加按钮?

作者:互联网

我对Android开发很新,只是遇到了偏好.
我找到了PreferenceScreens并希望用它创建一个登录功能.我唯一的问题是我不知道热,我可以在PreferenceScreen上添加一个“登录”按钮.
以下是我的Preference View的样子:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
...
    <PreferenceScreen android:title="@string/login" android:key="Login">
        <EditTextPreference android:persistent="true" android:title="@string/username" android:key="Username"></EditTextPreference>
        <EditTextPreference android:title="@string/password" android:persistent="true" android:password="true" android:key="Password"></EditTextPreference>
    </PreferenceScreen>
...
</PreferenceScreen>

Button应位于两个ExitTextPreferences下面.

这个问题有一个简单的解决方案吗?我找到的一个解决方案无法正常工作,因为我使用子偏好屏幕.

更新:

我发现我可以这样添加按钮:

<PreferenceScreen android:title="@string/login" android:key="Login">
        <EditTextPreference android:persistent="true" android:title="@string/username" android:key="Username"></EditTextPreference>
        <EditTextPreference android:title="@string/password" android:persistent="true" android:password="true" android:key="Password"></EditTextPreference>
        <Preference android:layout="@layout/loginButtons" android:key="loginButtons"></Preference>
</PreferenceScreen>

并且布局文件(loginButtons.xml)看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:weightSum="10" 
    android:baselineAligned="false" android:orientation="horizontal">
    <Button android:text="Login" android:layout_width="fill_parent"
        android:layout_weight="5" android:layout_height="wrap_content"
        android:id="@+id/loginButton" android:layout_gravity="left"></Button>
    <Button android:text="Password?" android:layout_width="fill_parent"
        android:layout_weight="5" android:layout_height="wrap_content"
        android:id="@+id/forgottenPasswordButton"></Button>
</LinearLayout>

所以现在按钮出现但我无法在代码中访问它们.
我尝试使用findViewById(),但这返回null.我有什么想法可以访问这些按钮?

解决方法:

对于xml:

<Preference android:title="Acts like a button"
                android:key="@string/myCoolButton"
                android:summary="This is a cool button"/>

然后为你的onCreate()中的java

Preference button = findPreference(getString(R.string.myCoolButton));
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {   
                    //code for what you want it to do   
                    return true;
                }
            });

这看起来像一个普通的偏好,只有一个标题和一个摘要,所以它看起来像它属于.

编辑:我改为使用@ string / myCoolButton和getString(R.string.myCoolButton),因为最好使用资源进行编译器辅助,语言翻译和String更改的简易性.

标签:android,android-button,android-preferences
来源: https://codeday.me/bug/20190918/1811568.html