我创建了一个titile_layout.xml,我想将TitleLayout用于Mainactivity。但是当我按下按钮时创建AlertDialog时,会出现如下错误。我想也许是#34; TitleLayout.this"?但如果我不使用它,我该怎么用?为什么呢?
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 :(得分:0)
第一个参数是Context对象。变化
new AlertDialog.Builder(TitleLayout.this);
与
new AlertDialog.Builder(getContext());
或将构造函数的Context对象标记为final并使用它
public TitleLayout(final Context context, AttributeSet attrs)
/// other code
new AlertDialog.Builder(context);
答案 1 :(得分:0)
Your Activity exetends LinearLayout
,因此它不提供任何上下文,context
实际上与您当前的网页相关,例如this
关键字。
只需使用
AlertDialog.Builder ad = new AlertDialog.Builder(context);