mirror of
https://github.com/SimpleMobileTools/Simple-Notes.git
synced 2025-06-05 17:00:23 +02:00
add a widget
This commit is contained in:
@ -1,6 +1,9 @@
|
||||
package notes.simplemobiletools.com;
|
||||
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
@ -47,12 +50,25 @@ public class MainActivity extends AppCompatActivity {
|
||||
private void saveText() {
|
||||
final String text = notesView.getText().toString().trim();
|
||||
prefs.edit().putString(Constants.TEXT, text).apply();
|
||||
|
||||
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
|
||||
hideKeyboard();
|
||||
updateWidget();
|
||||
}
|
||||
|
||||
private void hideKeyboard() {
|
||||
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
imm.hideSoftInputFromWindow(notesView.getWindowToken(), 0);
|
||||
}
|
||||
|
||||
private void updateWidget() {
|
||||
final Context context = getApplicationContext();
|
||||
final AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
|
||||
int[] ids = widgetManager.getAppWidgetIds(new ComponentName(context, MyWidgetProvider.class));
|
||||
|
||||
final Intent intent = new Intent(this, MyWidgetProvider.class);
|
||||
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
|
||||
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
|
||||
sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,27 @@
|
||||
package notes.simplemobiletools.com;
|
||||
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.appwidget.AppWidgetProvider;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.widget.RemoteViews;
|
||||
|
||||
public class MyWidgetProvider extends AppWidgetProvider {
|
||||
private static SharedPreferences prefs;
|
||||
|
||||
@Override
|
||||
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
|
||||
prefs = context.getSharedPreferences(Constants.PREFS, Context.MODE_PRIVATE);
|
||||
for (int widgetId : appWidgetIds) {
|
||||
updateWidget(context, appWidgetManager, widgetId);
|
||||
}
|
||||
super.onUpdate(context, appWidgetManager, appWidgetIds);
|
||||
}
|
||||
|
||||
private void updateWidget(Context context, AppWidgetManager widgetManager, int widgetId) {
|
||||
final String text = prefs.getString(Constants.TEXT, "");
|
||||
final RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
|
||||
remoteViews.setTextViewText(R.id.notesView, text);
|
||||
widgetManager.updateAppWidget(widgetId, remoteViews);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user