そのタイトルが私がやりたいことをどれだけうまく説明しているかはわかりませんが、ここに行きます。基本的に、ボタンのリストを実用的に作成するアプリがあります。ボタンをクリックすると、説明が返されます。
次のクラスを作成しました
public class DynamicOnClickListener implements OnClickListener
{
String description;
public DynamicOnClickListener(String adesc) {
//sets the description attribute at instantiation
this.description = adesc;
}
public void onClick(View v) {
//on button click returns dialog box with description in it
Log.v("DynamicOnClickListener","1");
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setMessage(description);
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
これはそのままで完全に機能しますが、ダイアログボックスを少しジャズアップしたいと思います。私はオンラインでいくつかの例を見てきましたが、Androidドキュメントによると、カスタムxmlレイアウトを定義し、LayourInflatorを使用してカスタムxmlをダイアログのビューとして設定することを提案しています。(それはとにかく私がそれを理解した方法です、おそらく間違って十分に正しいです)
ドキュメントの例は私のものとは少し異なりますが、彼らの例によると、次の行を追加する必要があります
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
ただし、これをクラスに追加すると、次のようになり、getActivity()でエラーが発生します。
public class DynamicOnClickListener implements OnClickListener
{
String description;
public DynamicOnClickListener(String adesc) {
//sets the description attribute at instantiation
this.description = adesc;
}
public void onClick(View v) {
//on button click returns dialog box with program description in it
Log.v("DynamicOnClickListener","1");
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.description_dialog, null));
builder.setMessage(description);
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}