人気ブログランキング | 話題のタグを見る
ブログトップ

智信の部屋

tomonobu.exblog.jp

プログラムに関する雑談なんかを書いていこうと思います。(android記事のまとめサイトはこちらです→http://tomonobu.rocketserver.jp/android_blog_index.php)

Android:ボタンのON/OFF

以前の「ボタンの設置とテキストボックスの内容の取得」で設置したボタンをON/OFFしてみよう。

 ・Buttonクラス で作成されたボタンに対して、
  そのアクションをON/OFFにするには、
  ViewクラスsetEnabled を使用して設定を行う。

サンプルコード
package com.tomonobu.application.test_3;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.LinearLayout;

public class Test_program_3Activity extends Activity {
private final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;
private final int FILL_PARENT = ViewGroup.LayoutParams.FILL_PARENT;
private final int button_id = 10000;
private final int button_set_id = 10001;
private boolean button_state = true;

protected void onCreate(Bundle icicle) {
super.onCreate(icicle);

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);

final EditText edit = new EditText(this);
final TextView tv = new TextView(this);

edit.setHeight(300);
edit.setText("Test test", BufferType.NORMAL);
linearLayout.addView(edit,
new LinearLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT));
Button button = new Button(this);
button.setText("設定");
button.setId(button_id);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SpannableStringBuilder sb = (SpannableStringBuilder)edit.getText();
tv.setText(sb.toString());
v.setEnabled(false);
}
});
Button button_set = new Button(this);
button_set.setText("OFF");
button_set.setId(button_set_id);
button_set.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Button button = (Button)findViewById(button_id);
Button button_set = (Button)findViewById(button_set_id);
if (button_state) {
button_state = false;
button_set.setText("ON");
button.setEnabled(false);
}
else {
button_state = true;
button_set.setText("OFF");
button.setEnabled(true);
}
}
});

linearLayout.addView(button,
new LinearLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT));
linearLayout.addView(button_set,
new LinearLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT));
linearLayout.addView(tv,
new LinearLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT));
}
}


by Tomonobu1979 | 2011-08-04 02:18 | android

by Tomonobu1979