コード例

Android用語集

カテゴリー: DialogInterface.OnClickListenerインターフェイス  閲覧数:357 配信日:2014-02-13 09:38


例1


(ダイアログ)ボタンをクリックしたときに、トーストを表示
・ボタンのイベント処理/無名クラス利用

▼ /HelloAndroid6/src/android/style/HelloAndroid6Activity.java
package android.style;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

public class HelloAndroid6Activity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// ダイアログの生成と表示
AlertDialog.Builder dlg =
new AlertDialog.Builder(this);
dlg.setTitle("sample"); // タイトル設定
dlg.setMessage("アラートダイアログ"); // メッセージ設定

// ボタン設定
dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(HelloAndroid6Activity.this,
"OKボタンクリック", Toast.LENGTH_LONG).show();//第1引数でHelloAndroid6Activityを指定している理由は、単にthisだけでは無名クラスのオブジェクトを指定したことになってしまうから
}
});
dlg.show(); // ダイアログの生成と表示
}

}


・xml … レイアウト
▼/HelloAndroid6/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

</LinearLayout>