2014-11-11 2 views
1

titile_layout.xml을 만들었으며 Mainactivity에 TitleLayout을 사용하려고합니다. 그러나 단추를 누를 때 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'의'Context'를 사용해야합니다. – Piyush

답변

0

첫 번째 매개 변수는 Context 개체입니다.

new AlertDialog.Builder(getContext()); 

new AlertDialog.Builder(TitleLayout.this); 

변경하거나 마지막으로 생성자의 컨텍스트의 개체를 표시하고 그것을

public TitleLayout(final Context context, AttributeSet attrs) 

/// other code 

new AlertDialog.Builder(context); 
+1

감사! 나는 getContext()를 사용한다. 괜찮아! – yxl

+0

당신은 환영합니다 – Blackbelt

0

Your Activity exetends LinearLayout 사용, 그래서 어떤 컨텍스트를 제공하지 않습니다, context 실제로 관련이 현재 페이지에 this과 같은 키워드를 추가하십시오. TitleLayout`는`Activity` 아니다`때문에

단순히

AlertDialog.Builder ad = new AlertDialog.Builder(context); 
관련 문제