2011-01-21 59 views
1

我试图将一些参数传递给AlertDialog,此对话框大多显示了这两个参数(假设“foo”和“bar”参数),并且我使用showDialog(int id)调用此对话框。在Activity类中有另一种方法,它采用Bundle对象传递参数:showDialog(int id, Bundle args),但此方法仅适用于API 8或更高版本,我需要使用API​​ 7.将参数传递给Android中的AlertDialog

在这里,我放了一些代码块使我所做的更容易。

在我的活动我创建AlertDialog这样的:

protected Dialog onCreateDialog(int id) { 
     final LayoutInflater factory = LayoutInflater.from(this); 

     switch(id) { 
     case DIALOG_ID: 
      final View view = factory.inflate(R.layout.dialog_layout, null); 
      final TextView fooValue = (TextView)view.findViewById(R.id.foo_label); 
      final TextView barValue = (TextView)view.findViewById(R.id.foo_label); 
      //fooLabel.setText("HERE MUST BE FOO PARAMETER VALUE"); 
      //barLabel.setText("HERE MUST BE BAR PARAMETER VALUE"); 

      return new AlertDialog.Builder(this). 
       setIcon(R.drawable.icon). 
       setTitle(R.string.app_name). 
       setView(view). 
       setPositiveButton(R.string.close, null). 
       create(); 
... 

而在另一部分我把这个对话框:

// THESE PARAMETERS MUST BE PASSED TO DIALOG 
    int foo = result.getInt("foo"); 
    String bar = result.getString("bar"); 

    showDialog(DIALOG_ID); 
... 

非常感谢您!

回答

2

我建议在实现上述onCreateDialog函数的类中添加一个方法setFooBar(int foo, String bar),以在调用showDialog之前接收foo和bar的值。

如果您没有活动的实例,请考虑使方法和变量静态。

-1

尝试这个例子

LayoutInflater factory = LayoutInflater.from(this); 
      final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);// this layout can created by yourself whatever you want. 
      return new AlertDialog.Builder(AlertDialogSamples.this) 
       .setIcon(R.drawable.alert_dialog_icon) 
       .setTitle(R.string.alert_dialog_text_entry) 
       .setView(textEntryView) 
       .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 

         /* User clicked OK so do some stuff */ 
        } 
       }) 
       .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 

         /* User clicked cancel so do some stuff */ 
        } 
       }) 
       .create(); 

layoutname:main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <TextView android:layout_width="fill_parent" android:textColor="#663355" 
     android:layout_height="wrap_content" android:hint="@string/hello" /> 
</LinearLayout>