gau*_*ssd 7 configuration android widget sharedpreferences
我想让用户在启动主屏幕小部件时定义用户名.但我在我的小部件中存储和访问此值时遇到了麻烦.我现在所做的是创建一个配置活动,它在创建窗口小部件时启动.因此我在清单文件中将其定义如下(我也在widgetprovider.xml中定义它):
<activity android:name=".ExampleAppWidgetConfigure">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
Run Code Online (Sandbox Code Playgroud)
然后,配置活动允许用户输入将存储在SharedPreferences
窗口小部件中的用户名:
SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE).edit();
prefs.putString("username", text);
prefs.commit();
Run Code Online (Sandbox Code Playgroud)
我的问题是如何获取此值?在我的widget类中,我希望有一个实例变量,如:
final String userName = ...; //load the username here.
Run Code Online (Sandbox Code Playgroud)
但是如何在我的小部件中检索用户名?问题是widget是AppWidgetProvider
我无法访问的子类SharedPreferences
(因为AppWidgetProvider
它不是子类Context
).我想将用户名存储在strings.xml文件中,这似乎也不可能.使用SharedPreferences
正确的方法吗?我还想过将用户名设置TextView
为我的小部件,后来应该显示用户名.但我需要在我的类中用于一些服务器请求的用户名,似乎没有办法获取TextView
小部件中的文本...只setTextViewText(String text)
定义了setter .
我该如何检索用户名?
chr*_*spr 11
您需要从上下文中获取SharedPreferences实例,该实例在窗口小部件提供程序的onUpdate()方法中提供.像这样的东西:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8746 次 |
最近记录: |