0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Androidを使い熟す!】Buttonについて

Posted at

#####※Android技術者認定にも役に立ちます!

#Button
タッチでイベントを発生させるViewの1つ

#Buttonクラス宣言

java
 Buttonクラスの変数
Button button = findViewById(R.id.button);

 Buttonクラスのインスタンス化
(コードで書く場合)
Button button = new Button(this);

#よく使う機能
・ボタン名セット

java
※直接導入
button.setText("文字");

※リソース
button.setText(R.string.text);

・クリックイベント

java
 onClickメソッド
extends Activity implements OnClickListener
button.setOnClickListener(this);
public void onClick(View v) {
    if (v == button){
        処理を入れる
    }
}
Tip
 if分ではなくswitch分も代わりによく使う。

※ボタンに直接セット
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        処理を入れる
    }
});

※リスナーセット
button.setOnClickListener(btnListener);
OnClickListener btnListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        処理を入れる
    }
};

xml
<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:onClick="clickButton" />

public void ClickButton(View view) {
    処理を入れる
}

#Tip
こんな書き方も?

java
public class OnClickEvent implements View.OnClickListener {

    private static final OnClickEvent instance = new OnClickEvent();

    private OnClickEvent() {
    }

    public static OnClickEvent getInstance() {
        return instance;
    }

    @Override
    public void onClick(View v) {
        if (v != null) {
            switch (v.getId()) {
                case R.id.button:
                    // クリック処理
                    break;
            }
        }
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);

    findViewById(R.id.button).setOnClickListener(OnClickEvent.getInstance());
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?