Androidカスタムダイアログの例
このチュートリアルでは、Androidでカスタムダイアログを作成する方法を示します。 次の手順を参照してください。
-
カスタムダイアログレイアウト(XMLファイル)を作成します。
-
レイアウトを
Dialogに添付します。 -
Dialogを表示します。 -
完了しました。
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.
Note
このcustom AlertDialog exampleもお読みください。
1 Androidレイアウトファイル
メイン画面用とカスタムダイアログ用の2つのXMLファイル。
ファイル:res / layout / main.xml
ファイル:res / layout / custom.xml
/>
2. アクティビティ
次のステップでコメントとデモを読んでください。それは自己探求的です。
ファイル:MainActivity.java
package com.example.android;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
final Context context = this;
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.buttonShowCustomDialog);
// add button listener
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
3. Demo
起動すると、「main.xml」レイアウトが表示されます。

ボタンをクリックし、カスタムダイアログ「custom.xml」レイアウトを表示します。「OK」ボタンをクリックすると、ダイアログボックスが閉じます。

ソースコードをダウンロード
ダウンロード–Android-Custom-Dialog-Example.zip(16 KB)