我是新手,我发现从字符串数组中获取文本很困难。我尝试在我的应用程序中创建一个小部件,我希望小部件从我在资源文件夹中声明的字符串数组更新它的文本视图,但这不会解决问题。这是我的代码。
MainActivity.Java
public class MainActivity extends AppCompatActivity {
public static TextView Quote;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Quote = (TextView) findViewById(R.id.appwidget_text);
final String[] Quotes = getResources().getStringArray(R.array.Qoutes);
Random rand = new Random();
int randNum = rand.nextInt(Quotes.length);
Quote.setText(Quotes[randNum]);
}}
NewAppWidget.java
public class NewAppWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = MainActivity.Quote.getText().toString();
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0 , intent, 0);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
remoteViews.setOnClickPendingIntent(R.id.interfaceID,pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}}
谢谢