2014-11-11 2 views
1

Я создал titile_layout.xml, и я хочу использовать TitleLayout в Mainactivity. Но когда я создаю AlertDialog, когда я нажимаю кнопку, появляется ошибка, как показано ниже. Я думаю, может быть, что-то не так с «TitleLayout.this»? но если я его не использую, что я должен использовать? Зачем?Конструктор AlertDialog.Builder (TitleLayout) не определен

package cn.example.uilayouttest; 

import android.app.AlertDialog; 
import android.app.AlertDialog.Builder; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder; 
import android.util.AttributeSet; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.widget.Button; 
import android.widget.LinearLayout; 
import android.widget.TextView; 

public class TitleLayout extends LinearLayout { 

    public TitleLayout(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     LayoutInflater.from(context).inflate(R.layout.title_layout, TitleLayout.this); 

     Button btn1 = (Button) findViewById(R.id.button1); 
     Button btn2 = (Button) findViewById(R.id.button2); 
     TextView tv = (TextView) findViewById(R.id.text_view); 

     btn1.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // The wrong is here:The constructor AlertDialog.Builder(TitleLayout) is undefined 
       AlertDialog.Builder ad = new AlertDialog.Builder(TitleLayout.this); 
       ad.setTitle("fefsfs"); 
       ad.setMessage("fefwefw"); 
       ad.setPositiveButton("fefw", new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         // TODO Auto-generated method stub 

        } 
       }); 
       ad.show(); 
      } 
     }); 
     btn2.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

      } 
     }); 


    } 
// public void onclick() 

} 
+0

Поскольку 'TitleLayout' не' Activity'. Вы должны использовать 'Context'' TitleLayout', создавая его конструктор. – Piyush

ответ

0

Первый параметр - объект контекста. Изменение

new AlertDialog.Builder(TitleLayout.this); 

с

new AlertDialog.Builder(getContext()); 

или пометить объект данного контекста конструктора в качестве окончательного и использовать его

public TitleLayout(final Context context, AttributeSet attrs) 

/// other code 

new AlertDialog.Builder(context); 
+1

Спасибо! Я использую getContext(). все хорошо! – yxl

+0

приветствуются – Blackbelt

0

Your Activity exetends LinearLayout, поэтому он не дает каких-либо контекста, context на самом деле связано на вашу текущую страницу, например, ключевое слово.

Просто используйте

AlertDialog.Builder ad = new AlertDialog.Builder(context); 
Смежные вопросы