簡體   English   中英

Android按日期月份和日期選擇字符串

[英]android select string by date month and day

在string.xml中,我添加了一些像這樣的字符串

<string name="m8d1">text sample</string>
<string name="m8d2">text sample</string>
<string name="m8d3">text sample</string>

我有一個小部件,我想按日期,月份和日期顯示字符串

public class Widget extends AppWidgetProvider {

    public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) { 
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH); 
        int day = calendar.get(Calendar.DAY_OF_MONTH); 

        String txt = context.getString(R.string.m"+month+"d"+day);

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
        remoteViews.setTextViewText(R.id.widgettext,txt);
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    }

您需要深入了解R.string.m的含義。 您將無法執行以下操作

String txt = context.getString(R.string.m"+month+"d"+day);

詳細說明-R文件包含靜態類stringstring類包含靜態整數成員m 沒有像鍵值對這樣的東西,所以您不能通過字符串訪問它。

編輯您可以使用此方法通過字符串獲取值-

private String getStringResourceByName(Context context,String name) { 
      int resId = context.getResources().getIdentifier(name, "string", context.getPackageName());
      return context.getString(resId);
    }

所以現在您將能夠擁有類似的東西-

String txt = getStringResourceByName(context,"m"+month+"d"+day);

希望這對您有幫助

String txt="m"+month+"d"+day;  
txt=context.getResources().getString(context.getResources().getIdentifier(txt, "string", getPackageName())); 

你必須使用

String txt = context.getResource().getString(R.string.m)+month+"d"+day;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM