我对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 . 我有什么想法可以访问这些按钮?
8 回答
对于xml:
然后为你的
onCreate()
中的java这看起来像一个普通的偏好,只有一个 Headers 和一个摘要,所以它看起来像它属于 .
Edit: 我改为使用
@string/myCoolButton
和getString(R.string.myCoolButton)
,因为最好使用资源进行编译器辅助,语言翻译和字符串更改的简易性 .我想添加一个退出链接到首选项,并能够修改Jakar的代码,使其工作如下:
最初的'偏好'是我编辑过的'EditTextPreference' .
然后在课堂上:
我太迟了 . 这就是我为Button Preference所做的 .
在xml文件夹中的preference.xml文件中的首选项
和布局文件夹中的pref_reset_bd_button.xml
加
下面
buttonLayout:
访问按钮:
您可以通过将按钮放在RelativeLayout中来获取屏幕顶部或底部的按钮:
top_control_bar
bottom_control_bar
bottom_control_bar
这对我有用 . 我希望我能用这段代码帮助别人 .
我认为没有一种简单的方法可以将按钮添加到首选项屏幕 . 偏好仅限于:
在使用首选项屏幕时,您只能使用这些选项,并且没有单一的“按钮首选项”可以轻松满足您的需求 .
我一直在寻找类似的功能,在首选项屏幕上添加按钮,但似乎您需要为此构建自己的屏幕,在您自己的实现中管理对首选项的更改 .
你可以这样做来访问按钮!
不要忘记将
android:id
添加到包含 layoutButtons.xml 中按钮的LinearLayout,即android:id="@+id/mylayout"
尝试android:onClick =“myMethod”就像一个简单的onclick事件的魅力
您还可以通过覆盖
Preference.onCreateView(parent)
来自定义首选项的布局 . 下面的示例使用匿名内部类来创建红色首选项 .您可以使用此技术将按钮添加到默认视图 .