所以基本上,我有一个简单的应用程序小部件,它显示文件中的值并每 24 小时更新一次。它可以正常工作,但是我想将刷新按钮添加到我的小部件中,并且每次单击该按钮时都想调用 onUpdate 。我一直在寻找一些答案,但它们似乎与我想要做的不匹配。
AppWidgetProvider
public class NewAppWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
//Petlja za id-ove
String prosek = citaIzFajla(context);
final int N = appWidgetIds.length;
for(int i=0; i<N; i++){
int awID = appWidgetIds[i];
RemoteViews v = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
v.setTextViewText(R.id.widget_text, prosek);
appWidgetManager.updateAppWidget(awID, v);
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
Toast.makeText(context, "Deleted widget", Toast.LENGTH_LONG).show();
}
public void refreshButtonClick(View v){
//I need code that goes here to call onUpdate()
}
public String readFromFile(Context c) {
String out = "fail";
String fileName = "PROSEK";
try {
FileInputStream fileIS = c.openFileInput(fileName);
try {
int size = fileIS.available();
byte[] bufferReader = new byte[size];
fileIS.read(bufferReader);
fileIS.close();
out = new String(bufferReader);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return out;
}
}
小部件的 xml 文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="5dp"
android:background="#cbcfd6">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="2dp"
android:background="#000000">
<Button
android:id="@+id/widget_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh"
android:onClick="refreshButtonClick"/>
<TextView
android:id="@+id/widget_prosek"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="#ffffff"
android:text="Prosek:"
android:textSize="28dp"
android:textAlignment="center"/>
<TextView
android:id="@+id/widget_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ffffff"
android:text="Example"
android:textSize="28dp"
android:gravity="right"
/>
</LinearLayout>
</LinearLayout>
对不起,我的英语不好。