📜 ⬆️ ⬇️

Calling an Alertdialog from a widget

While developing my widget, I wanted some information to be provided to the user in the form of a pop-up dialog (alertdialog), but faced with a feature of the platform. Android does not allow calling an alertdialog from the AppWidgetProvider.
How to write a simple widget can be viewed in this article . Let's go ahead and immediately consider how to get around this limitation.

The method found is very simple: you cannot call alertdialog, but you can call activity.

Create a markup activity. Layout / act.xml file

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> </LinearLayout> 

')
We register activity in AndroidManifest.xml by adding to the application section

 <activity android:name="act" android:label="@string/app_name" /> 


Create a class of our activity. The file act.java. When you call activity, it will show alertdialog and close after clicking on any of the buttons.

 import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.view.Window; import android.widget.Toast; public class act extends Activity { final int DIALOG_EXIT = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //  activity requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.act); // alertdialog showDialog(DIALOG_EXIT); } protected Dialog onCreateDialog(int id) { if (id == DIALOG_EXIT) { AlertDialog.Builder adb = new AlertDialog.Builder(this); //  adb.setTitle("Title"); adb.setMessage("Message"); adb.setIcon(android.R.drawable.ic_dialog_info); //  adb.setPositiveButton("Yes", myClickListener); adb.setNegativeButton("No", myClickListener); //    (    activity ) adb.setCancelable(false); return adb.create(); } return super.onCreateDialog(id); } OnClickListener myClickListener = new OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { //  "Yes" case Dialog.BUTTON_POSITIVE: Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show(); // activity finish(); break; case Dialog.BUTTON_NEGATIVE: Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_SHORT).show(); finish(); break; } } }; } 


In the event click on the button of the widget indicate the call activity

 Intent i = new Intent(context, act.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); 


The most important part is making the activity transparent by changing the theme in AndroidManifest.xml

 <activity android:name="act" android:label="@string/app_name" android:theme="@android:style/Theme.Translucent" /> 

Result:

Source: https://habr.com/ru/post/164851/


All Articles