This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:app="http://schemas.android.com/apk/res-auto" | |
xmlns:tools="http://schemas.android.com/tools" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
tools:context=".MainActivity"> | |
<Button android:id="@+id/buttonStart" | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
android:text="Start" | |
android:onClick="start" | |
app:layout_constraintBottom_toBottomOf="parent" | |
app:layout_constraintLeft_toLeftOf="parent" | |
app:layout_constraintRight_toRightOf="parent" | |
app:layout_constraintTop_toTopOf="parent" /> | |
</androidx.constraintlayout.widget.ConstraintLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.asyncetask; | |
import androidx.appcompat.app.AppCompatActivity; | |
import android.content.Context; | |
import android.os.AsyncTask; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.Toast; | |
public class MainActivity extends AppCompatActivity { | |
Button mButtonStart; | |
private class CountingTask extends AsyncTask<Integer, Integer, Integer> { | |
@Override | |
protected Integer doInBackground(Integer... params) { | |
int count = params[0]; | |
for (int x = 0; x < count; x++) { | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
return count; | |
} | |
@Override | |
protected void onPostExecute(Integer returnVal) { | |
super.onPostExecute(returnVal); | |
Context context = getApplicationContext(); | |
CharSequence text = "Start again!"; | |
int duration = Toast.LENGTH_SHORT; | |
Toast toast = Toast.makeText(context, text, duration); | |
toast.show(); | |
mButtonStart.setEnabled(true); | |
} | |
} | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
mButtonStart = findViewById(R.id.buttonStart); | |
} | |
public void start(View view) { | |
mButtonStart.setEnabled(false); | |
new CountingTask().execute(10); | |
} | |
} |
0 Comments