Skip to content

Async with Vew Inflate

Yuri Shmakov edited this page Aug 15, 2017 · 6 revisions

MainActivity.java:

public class MainActivity extends MvpAppCompatActivity implements HelloWorldView {
	@InjectPresenter
	HelloWorldPresenter mHelloWorldPresenter;
	private TextView mTimerTextView;
	private View mMessageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mTimerTextView = (TextView) findViewById(R.id.timer_text_view);
	}

	@Override
	public void showTimer() {
		mTimerTextView.setVisibility(View.VISIBLE);
	}

	@Override
	public void hideTimer() {
		mTimerTextView.setVisibility(View.GONE);
	}

	@Override
	public void setTimer(int seconds) {
		mTimerTextView.setText(getString(R.string.timer, seconds));
	}

	@Override
	public void showMessage(int message) {
		ViewGroup rootView = (ViewGroup) findViewById(R.id.activity_main);
		mMessageView = LayoutInflater.from(this).inflate(R.layout.item_message, rootView, false);
		rootView.addView(mMessageView);

		((TextView) mMessageView.findViewById(R.id.message_text_view)).setText(message);
		mMessageView.findViewById(R.id.close_button).setOnClickListener(view -> mHelloWorldPresenter.onDismissMessage());
	}

	@Override
	public void hideMessage() {
		ViewGroup rootView = (ViewGroup) findViewById(R.id.activity_main);
		rootView.removeView(mMessageView);
	}
}

HelloWorldPresenter.java:

@InjectViewState
public class HelloWorldPresenter extends MvpPresenter<HelloWorldView> {
	public HelloWorldPresenter() {
		AsyncTask<Void, Integer, Void> asyncTask = new AsyncTask<Void, Integer, Void>() {
			@Override
			protected void onPreExecute() {
				getViewState().showTimer();
			}

			@Override
			protected Void doInBackground(Void... voids) {
				for (int i = 2; i > 0; i--) {
					publishProgress(i);
					sleepSecond();
				}
				return null;
			}

			@Override
			protected void onProgressUpdate(Integer... values) {
				getViewState().setTimer(values[0]);
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				getViewState().hideTimer();
				getViewState().showMessage(R.string.hello_world);
			}

			private void sleepSecond() {
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					// pass
				}
			}
		};

		asyncTask.execute();
	}

	public void onDismissMessage() {
		getViewState().hideMessage();
	}
}

HelloWorldView.java:

@StateStrategyType(AddToEndSingleStrategy.class)
public interface HelloWorldView extends MvpView {
	void showTimer();

	void hideTimer();

	void setTimer(int seconds);

	void showMessage(int message);

	void hideMessage();
}