Диалог пользовательского прогресса со скругленным поворотом изображения с помощью AsynTask
Я создал настраиваемый диалог "Прогресс загрузки". И его работа хорошо.
Я вращаю 12 квадратных изображений. Вот один из них.
![enter image description here]()
Но когда я хочу использовать его с AsynTask, анимация не работает.
Мой примерный код ниже.
Деятельность, где я начинаю загрузку... Анимация и остановка.
MainActivity.java
public class MainActivity extends Activity {
AnimationDrawable loadingViewAnim;
TextView loadigText;
ImageView loadigIcon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadigText = (TextView) findViewById(R.id.textView1);
loadigText.setText("Loading...");
loadigText.setVisibility(View.GONE);
loadigIcon = (ImageView) findViewById(R.id.imageView1);
loadigIcon.setVisibility(View.GONE);
loadigIcon.setBackgroundResource(R.anim.progress_animation_white);
loadingViewAnim = (AnimationDrawable) loadigIcon.getBackground();
}
//When User Touch on Screen The Loading... Animation Starts With Image Rotation
//If I start below code in AsynTask onPreExecute method it doesn't work
public boolean onTouchEvent(MotionEvent event)
{
loadigText.setVisibility(View.VISIBLE);
loadigIcon.setVisibility(View.VISIBLE);
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
loadingViewAnim.start();
return true;
}
return super.onTouchEvent(event);
}
}
XML-макет с помощью простого текста и изображения для диалогового окна "Прогресс".
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/progress_sm_w01" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Loading..."
android:textColor="#ffffff"
android:textSize="12sp" />
</LinearLayout>
Анимационный список с 12 изображениями Я вращаюсь с углом и продолжительностью времени
progress_animation_white.xml
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/progress_sm_w01" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w02" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w03" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w04" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w05" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w06" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w07" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w08" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w09" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w10" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w11" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w12" android:duration="50" />
</animation-list>
Вот результат загрузки экрана.
![enter image description here]()
Мой вопрос: все равно, чтобы достичь той же анимации загрузки с AsynTask.
Ваша небольшая помощь будет оценена.
Ответы
Ответ 1
Хорошо спасибо @Brontok и @URAndroid за помощь. Я решил свою проблему.
Поэтому позвольте мне ответить на мой собственный вопрос, Hoe я достиг этой пользовательской загрузки анимации
Я добавил несколько изображений для анимации вращения изображений
Шаг 1 - в папке res/drawable
- progress_sm_w00.png(пустое прозрачное изображение по умолчанию)
- progress_sm_w01.png(первая позиция анимации)
- progress_sm_w02.png
- progress_sm_w03.png
- progress_sm_w04.png
- progress_sm_w05.png
- progress_sm_w06.png
- progress_sm_w07.png
- progress_sm_w08.png
- progress_sm_w09.png
- progress_sm_w10.png
- progress_sm_w11.png
- progress_sm_w12.png(последняя позиция анимации).
Пример: один из них ниже, я добавил
![enter image description here]()
Шаг 2 - в папке res/anim создан имя файла анимации "loading_animation.xml"
<item android:drawable="@drawable/progress_sm_w01" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w02" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w03" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w04" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w05" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w06" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w07" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w08" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w09" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w10" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w11" android:duration="50" />
<item android:drawable="@drawable/progress_sm_w12" android:duration="50" />
</animation-list>
Шаг 3 - теперь создал пользовательскую загрузку макета просмотра на моем экране (активность) везде, где мне нужно показать загрузку
Пример.
XML-макет для моего экрана входа в Facebook
<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#0D000000"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ImageView
android:id="@+id/imageView111"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/progress_sm_w00"
android:visibility="gone" />
<TextView
android:id="@+id/textView111"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Searching..."
android:textColor="#ffffff"
android:textSize="12sp"
android:visibility="gone" />
</LinearLayout>
Шаг 4 - В java-коде (Activity) Я создал загрузку и после завершения метода OnCreate я начал Asyn Task, чтобы моя анимация работала правильно.
public class ResultActivity extends Activity {
private static final String TAG = "ResultActivity";
private AnimationDrawable loadingViewAnim=null;
private TextView loadigText = null;
private ImageView loadigIcon = null;
private LinearLayout loadingLayout = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
loadingLayout = (LinearLayout)findViewById(R.id.LinearLayout1);
loadingLayout.setVisibility(View.GONE);
loadigText = (TextView) findViewById(R.id.textView111);
loadigText.setVisibility(View.GONE);
loadigIcon = (ImageView) findViewById(R.id.imageView111);
loadigIcon.setVisibility(View.GONE);
loadigIcon.setBackgroundResource(R.anim.loading_animation);
loadingViewAnim = (AnimationDrawable) loadigIcon.getBackground();
// This line is to start Asyn Task only when OnCreate Method get completed, So Loading Icon Rotation Animation work properly
loadigIcon.post(new Starter());
}
class Starter implements Runnable {
public void run() {
//start Asyn Task here
new LongOperation().execute("");
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
//ToDo your Network Job/Request etc. here
return "Executed";
}
@Override
protected void onPostExecute(String result) {
//ToDo with result you got from Task
//Stop Loading Animation
loadingLayout.setVisibility(View.GONE);
loadigText.setVisibility(View.GONE);
loadigIcon.setVisibility(View.GONE);
loadingViewAnim.stop();
}
@Override
protected void onPreExecute() {
//Start Loading Animation
loadingLayout.setVisibility(View.VISIBLE);
loadigText.setVisibility(View.VISIBLE);
loadigIcon.setVisibility(View.VISIBLE);
loadingViewAnim.start();
}
@Override
protected void onProgressUpdate(Void... values) {}
}
}
Шаг 5 - Вот экран результатов с анимацией Progress Loading.
![enter image description here]()
Надеюсь, это поможет вам. Ура!!
Ответ 2
Возможно, вы можете использовать GLIDE, например
Glide.with(context)
.load(imageUrl)
.asGif()
.placeholder(R.drawable.loading2)
.crossFade()
.into(imageView);
Показать GIF файл с помощью Glide (библиотека загрузки и кеширования изображений)
Ответ 3
MainActivity
package com.sanjay.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.sanjay.R;
public class MainActivity extends AppCompatActivity {
CustomProgressDialog customProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customProgressDialog = new CustomProgressDialog(this);
}
public void onClickShowDialog(View view) {
customProgressDialog.show();
}
public void onClickDismissDialog(View view) {
if (customProgressDialog != null && customProgressDialog.isShowing()) {
customProgressDialog.dismiss();
}
}
}
CustomProgressDialog
package com.sanjay.activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.sanjay.R;
public class CustomProgressDialog extends Dialog {
private ImageView imageView;
private Context mContext;
public CustomProgressDialog(Context context) {
super(context, R.style.CustomProgressDialog);
mContext = context;
WindowManager.LayoutParams wlmp = getWindow().getAttributes();
wlmp.gravity = Gravity.CENTER_HORIZONTAL;
getWindow().setAttributes(wlmp);
setTitle(null);
setCancelable(true);
//setOnCancelListener(null);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(400, 400);
imageView = new ImageView(context);
imageView.setBackgroundResource(R.drawable.custom_dialog);
layout.addView(imageView, params);
addContentView(layout, params);
}
@Override
public void show() {
super.show();
AnimationDrawable frameAnimation = (AnimationDrawable) imageView.getBackground();
frameAnimation.start();
}
@Override
public void dismiss() {
super.dismiss();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<Button
android:id="@+id/btn_show_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:onClick="onClickShowDialog"
android:text="Show Dialog" />
<Button
android:id="@+id/btn_dismiss_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_show_dialog"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:onClick="onClickDismissDialog"
android:text="Dismiss Dialog" />
</RelativeLayout>
Рез/вытяжка/custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item
android:drawable="@drawable/image_1"
android:duration="200" />
<item
android:drawable="@drawable/image_2"
android:duration="200" />
<item
android:drawable="@drawable/image_3"
android:duration="200" />
<item
android:drawable="@drawable/image_4"
android:duration="200" />
<item
android:drawable="@drawable/image_5"
android:duration="200" />
<item
android:drawable="@drawable/image_6"
android:duration="200" />
<item
android:drawable="@drawable/image_7"
android:duration="200" />
<item
android:drawable="@drawable/image_8"
android:duration="200" />
</animation-list>