Pull to refresh

Вызов Alertdialog из виджета

Reading time 2 min
Views 4.3K
Разрабатывая свой виджет я захотел чтобы некоторая информация предоставлялась пользователю в виде всплывающего диалога(alertdialog), но столкнулся с особенность платформы. Android не позволяет вызывать alertdialog из AppWidgetProvider.
Как написать простой виджет можно посмотреть в этой статье. Пойдем дальше и сразу рассмотрим как обойти это ограничение.

Способ нашел очень простой: alertdialog вызвать нельзя, но можно вызвать activity.

Создаём разметку activity. Файл layout/act.xml.

<?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>


Регистрируем activity в AndroidManifest.xml добавив в секцию application

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


Создаём класс нашего activity. Файл act.java. При вызове activity оно покажет alertdialog и закроется после нажатия на любую из кнопок.

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;
		        }
		      }
		    };
		  
}


В событие нажатие на кнопку виджета указываем вызов activity

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


Самая важная часть, делаем activity прозрачным изменив в AndroidManifest.xml тему

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

Результат:
Tags:
Hubs:
+2
Comments 4
Comments Comments 4

Articles