레이아웃
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.buttondisabletest.MainActivity" >
<Button
android:id="@+id/btn_0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Button1" />
<Button
android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_0"
android:layout_centerHorizontal="true"
android:text="Button2" />
<Button
android:id="@+id/btn_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_1"
android:layout_centerHorizontal="true"
android:text="Button3" />
</RelativeLayout>
액티비티
MainActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private static final int BUTTON_COUNT = 3;
private View[] mButtons;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtons = new Button[BUTTON_COUNT];
final String format = "btn_%d";
for (int i = 0; i < BUTTON_COUNT; i++) {
int id = getResources().getIdentifier(String.format(format, i), "id", getPackageName());
mButtons[i] = findViewById(id);
mButtons[i].setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
doWork(v.getId() - R.id.btn_0);
}
private void doWork(int position) {
if (flagWorking) {
return;
}
for (int i = 0; i < BUTTON_COUNT; i++) {
mButtons[i].setEnabled(i == position);
}
flagWorking = true;
new MyTask().execute(position);
}
private boolean flagWorking = false;
private class MyTask extends AsyncTask<Integer, Void, Void> {
@Override
protected Void doInBackground(Integer... params) {
Log.v(getClass().getSimpleName(), "works while 3 sec... position: " + params[0]);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.v(getClass().getSimpleName(), "finished work. " + params[0]);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
flagWorking = false;
for (int i = 0; i < BUTTON_COUNT; i++) {
mButtons[i].setEnabled(true);
}
}
}
}