ANDROID: Как ждать клика на Alert Dialog?
Я подготовил AsyncTask с Alert Dialog, в котором есть кнопка Да / Нет. Мне нужно вернуть 1 для Да и 0 для Нет. Я не полностью понимаю AsyncTask. Что нужно сделать, чтобы добавить время ожидания для клика? Текущее состояние не ждет
КОД КЛАССА:
class MyTask extends AsyncTask<Void,Integer,Integer> {
TextView ozn_=null;
AlertDialog dialog=null;
AlertDialog.Builder builder=null;
ImageView icon=null;
int ret=0;
public int getRetValue(){
return ret;
}
public MyTask(int a){
ret=a;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
ozn_ = new TextView(LoginActivity.this);
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
ImageView icon = new ImageView(LoginActivity.this);
icon.setBackgroundResource(R.drawable.warn);
builder.setMessage("oznam");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(set_dp(60), set_dp(60));
icon.setLayoutParams(params);
ozn_.setGravity(Gravity.LEFT);
LinearLayout l1 = new LinearLayout(LoginActivity.this);
l1.setPadding(set_dp(12), set_dp(12), set_dp(12), set_dp(20));
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setGravity(Gravity.CENTER_VERTICAL);
ozn_.setPadding(set_dp(12), 0, 0, 0);
l1.addView(icon);
l1.addView(ozn_);
builder.setView(l1);
builder.setPositiveButton("Áno", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
publishProgress(11); //somewhere here is needed control of wait
getResources().notifyAll();
dialog.dismiss();
}
});
builder.setNegativeButton("Nie", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
publishProgress(222); //somewhere here is needed control of wait
getResources().notifyAll();
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(0xff00b300);
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(0xffd56300);
}
});
dialog.setCancelable(false); //backbutton
dialog.setCanceledOnTouchOutside(false); //klick outside dialog
dialog.show();
}
@Override
protected Integer doInBackground(Void... rets) {
return ret;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate();
ret++;
}
@Override
protected void onPostExecute(Integer aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(LoginActivity.this, "post"+ret, Toast.LENGTH_SHORT).show();
}
}
КОД В ДЕЯТЕЛЬНОСТИ:
a=654; MyTask task=new MyTask(a); task.execute(); a=task.getRetValue();
3 ответа
РЕШИТЬ!
Это решение действительно ожидает события щелчка и возвращает значение.
private boolean resultValue;
public boolean getDialogValueBack(Context context)
{
final Handler handler = new Handler()
{
@Override
public void handleMessage(Message mesg)
{
throw new RuntimeException();
}
};
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Title");
alert.setMessage("Message");
alert.setPositiveButton("Return True", new
DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
resultValue = true;
handler.sendMessage(handler.obtainMessage());
}
});
alert.setNegativeButton("Return False", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
resultValue = false;
handler.sendMessage(handler.obtainMessage());
}
});
alert.show();
try{ Looper.loop(); }
catch(RuntimeException e){}
return resultValue;
}
Я не мог понять ваш вопрос. Но обычно Asynctask выглядит так. Здесь я добавил интерфейс обратного вызова, чтобы получить результат обратно. Если у вас есть время, чтобы попробовать это. Пожалуйста...
public class AsyncGet extends AsyncTask<Void, Void, String> {
public interface AsyncGetResponse {
void processFinish(String result);
}
private AsyncGetResponse asyncGetResponse = null;
public AsyncGet(AsyncGetResponse asyncGetResponse) {
this.asyncGetResponse = asyncGetResponse;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog. If you need
}
@Override
protected String doInBackground(Void... voids) {
String result = null;
// do your background work here. Like API calls.
return result;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// update progress percentage. If you need.
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// hide progress dialog. If showing.
// pass result value.
if (asyncGetResponse != null) {
asyncGetResponse.processFinish(result);
}
}
}
Как позвонить в AsyncGet.java, смотрите ниже.
new AsyncGet(new AsyncGet.AsyncGetResponse() {
@Override
public void processFinish(String result) {
// process result from Async task.
}
}).execute();
Удачного кодирования...
Мне нужен класс для 4 типов AlertDialog (Предупреждение, Информация, Успех, Вопрос). первые 3 типа не нуждаются в возвращаемом значении, но 4-й тип требует возврата (кнопка Да / Нет). Поэтому мне нужно приостановить MainThread и запустить AsyncTask, чтобы нажать кнопку... КОД:
int a = 654;
MyTask task = new MyTask(a);
a=task.execute().get();
Toast.makeText(activity, "value " + a, Toast.LENGTH_SHORT).show();
Этот код в Activity действительно ждет doInBackground, пока не будет выполнен CODE:
@Override
protected Integer doInBackground(Void... tt) {
return 123;
}
Тост показывает значение 123, а не 654, поэтому этот код подходит. Но как вернуть переменную ret, которая должна быть установлена из Dialog, созданного и показанного из onPreExecute()?
КОД:
@Override
protected void onPreExecute() {
super.onPreExecute();
ozn_ = new TextView(LoginActivity.this);
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
ImageView icon = new ImageView(LoginActivity.this);
icon.setBackgroundResource(R.drawable.warn);
builder.setMessage("oznam");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(set_dp(60), set_dp(60));
icon.setLayoutParams(params);
ozn_.setGravity(Gravity.LEFT);
LinearLayout l1 = new LinearLayout(LoginActivity.this);
l1.setPadding(set_dp(12), set_dp(12), set_dp(12), set_dp(20));
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setGravity(Gravity.CENTER_VERTICAL);
ozn_.setPadding(set_dp(12), 0, 0, 0);
l1.addView(icon);
l1.addView(ozn_);
builder.setView(l1);
builder.setPositiveButton("Áno", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ret=11; //somewhere here is needed control of wait
dialog.dismiss();
}
});
builder.setNegativeButton("Nie", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ret=222; //somewhere here is needed control of wait
dialog.dismiss();}
});
final AlertDialog dialogt = builder.create();
dialogt.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
dialogt.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(0xff00b300);
dialogt.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(0xffd56300);
}
});
dialogt.setCancelable(false); //backbutton
dialogt.setCanceledOnTouchOutside(false); //klick outside dialog
dialogt.show();
}