2013-12-19 2 views
0

Я создаю пользовательский диалог, имеющий этот макет (название с изображением, текст, 2 кнопки):андроид - Диалог не работает

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center_vertical|center_horizontal" 
    android:background="@color/white"> 
    <RelativeLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingLeft="30dip" 
     android:paddingTop="10dip"> 
     <ImageView 
      android:id="@+id/dialog_title_image" 
      android:layout_alignParentLeft="true" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:background="@drawable/info"/> 
     <TextView 
      android:id="@+id/dialog_title" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="10dip" 
      android:layout_centerInParent="true" 
      android:text="Title" 
      android:layout_toRightOf="@id/dialog_title_image" 
      android:textColor="@color/black" 
      android:textSize="30sp"/> 

    </RelativeLayout> 
    <TextView 
      android:layout_width="fill_parent" 
      android:layout_height="2dip" 
      android:background="@color/header_grep" 
      android:layout_marginTop="5dip"/> 
    <TextView 
     android:id="@+id/dialog_msg" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:textColor="@color/dark_gray" 
     android:layout_marginTop="10dip" 
     android:layout_marginLeft="10dip"/> 

    <RelativeLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingTop="10dip" 
     android:gravity="bottom|center_horizontal" 
     android:paddingBottom="5dip"> 
     <Button 
      android:id="@+id/positive_button" 
      android:layout_alignParentLeft="true" 
      android:layout_width="100dip" 
      android:layout_height="wrap_content" 
      style="@style/Gradient" 
      android:text="Si"/> 
     <Button 
      android:id="@+id/negative_button" 
      android:layout_width="100dip" 
      style="@style/Gradient" 
      android:layout_height="wrap_content" 
      android:layout_toRightOf="@id/positive_button" 
      android:text="No"/> 
    </RelativeLayout> 


</LinearLayout> 

Это CustomDialog.java

public class CustomDialog extends Dialog { 

    Context context; 

    public CustomDialog(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
     this.context = context; 
    } 


    public CustomDialog(Context context, int theme) { 
     super(context, theme); 
     // TODO Auto-generated constructor stub 
     this.context = context; 
    } 


    public CustomDialog(Context context, boolean cancelable, 
      OnCancelListener cancelListener) { 
     super(context, cancelable, cancelListener); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     this.setContentView(R.layout.custom_dialog); 
    } 

} 

и это это метод я уже реализован, чтобы показать:

 private void showDialog(String msg, String title) 

    { 
     final Dialog dialog = new CustomDialog(this); 
     dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     dialog.setContentView(R.layout.custom_dialog); 

    TextView title_dialog = (TextView) dialog.findViewById (R.id.dialog_title); 
    title_dialog.setText(title); 

    TextView text = (TextView) dialog.findViewById(R.id.dialog_msg); 
    text.setText(msg); 

    Button positiveButton = (Button) dialog.findViewById(R.id.positive_button); 
    Button negativeButton = (Button) dialog.findViewById(R.id.negative_button); 

    positiveButton.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View arg0) { 

      finish(); 
     } 

    }); 

    negativeButton.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View arg0) { 

      dialog.dismiss(); 
     } 

    }); 

    dialog.show(); 

} 

, когда я запустить приложение и отображается диалоговое окно, заголовок и текст в том, что поразрядное d в файле xml (так что «Заголовок» и ничего для тела диалога), и если я нажимаю на кнопки, ничего не происходит. Может ли кто-нибудь мне помочь? Заранее спасибо.

+2

Попробуйте 'final Dialog dialog = new Dialog (YourActivity.this);' –

+1

Спасибо, парень! Он работает сейчас! Можете ли вы объяснить мне, что я сделал неправильно? – SegFault

+0

@SegFault Какие изменения вы внесете, чтобы заставить его работать? – keshav

ответ

1

Вы должны передать контекст приложения в диалоге. Если вы передали это как контекст и вы вызвали customdialog из события onclick(), то он ссылается на него как на объект onclicklistner(), и это неправильно. поэтому вы должны передать свою деятельность или контекст вашего приложения.

final Dialog dialog = new CustomDialog(yourappliactioncontext); 
0

Попробуйте:

final Dialog dialog = new Dialog(YourActivity.this);

вместо

final Dialog dialog = new Dialog(context);

Если вы собираетесь повторно использовать этот код, как повторно используемый компонент или как механизм создания диалоги в нескольких местах, создать базовый класс активности и использовать этот метод там и использовать его в подклассифицированных действиях по мере необходимости.

Смежные вопросы