2012-11-23 24 views
1

這是我的佈局如何把我的自定義數字選擇器在對話框中?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <net.simonvt.widget.NumberPicker 
     android:id="@+id/numberPicker" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="100dp" > 
    </net.simonvt.widget.NumberPicker> 

</RelativeLayout> 

它顯示在我的應用程序的自定義選擇器。但我想在對話框中顯示這個選擇器。

這是我的自定義對話框:

public class NumberPickerCustomDialog extends DialogFragment { 
@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    builder.setMessage("Dialog") 
      .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
       } 
      }) 
      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
       } 
      }).; 
    return builder.create(); 
} 

我怎樣才能把我的選擇器在此對話框?

謝謝!

回答

3

您需要在對話框中提供自定義佈局,這樣做可以獲取LayoutInflater服務並使用它來充氣佈局。

public class NumberPickerCustomDialog extends DialogFragment { 
Context context; 

@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // get context 
    context = getActivity().getApplicationContext(); 
    // make dialog object 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    // get the layout inflater 
    LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    // inflate our custom layout for the dialog to a View 
    View view = li.inflate(R.layout.my_custom_view, null); 
    // inform the dialog it has a custom View 
    builder.setView(view); 
    // and if you need to call some method of the class 
    MyCustomView myView = (MyCustomView) view.findViewById(R.id.custom_id_in_my_custom_view); 
    myView.doSome("stuff"); 
    // create the dialog from the builder then show 
    return builder.create(); 
} 
} 
+0

在這個例子中,什麼是MyCustomView?它包含什麼?謝謝。 – androidevil

+1

MyCustomView可以是您的NumberPicker(net.simonvt.widget.NumberPicker)或您佈局中的任何其他自定義類......我只是不知道您是否需要對您的NumberPicker對象進行編程式引用,對不起,我傾向於使用泛型可能的:P – JBirdVegas

+1

一個實用的用法在這裏http://gerrit.sudoservers.com/#/c/4248/9/src/com/aokp/romcontrol/github/CommitViewerDialog.java 74-92行 – JBirdVegas

相關問題