错误:无法引用在不同方法中定义的内部类中的非最终变量名称

时间:2014-05-01 13:21:38

标签: android textview onclicklistener android-alertdialog

你好我的朋友)我班上有下一个错误...

public class AlertDlg {
public static void AlertShow(final Activity activity, EditText name, EditText track)
{
    LayoutInflater inflater = activity.getLayoutInflater();
    View alertLayout = inflater.inflate(R.layout.layout_custom_dialog, null);
    name = (EditText) alertLayout.findViewById(R.id.et_name);
    track = (EditText) alertLayout.findViewById(R.id.et_track);
    AlertDialog.Builder alert = new AlertDialog.Builder(activity);
    alert.setTitle("Add track number");
    //alert.setIcon(R.drawable.plus);
    alert.setView(alertLayout);
    alert.setCancelable(false);
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(activity.getBaseContext(), "Abort", Toast.LENGTH_SHORT).show();
        }
    });
    alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
    ERROR HERE--->String sname = name.getText().toString();
            //String track = etPassword.getText().toString();
            Toast.makeText(activity.getBaseContext(), "Name: " + sname +"  "+  " Track: " , Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog dialog = alert.create();
    dialog.show();
}}

错误:无法在不同方法中定义的内部类中引用非最终变量名。我试图从EditText获取数据。但得到这个错误......

调用方法:

AlertDlg.AlertShow(MainActivity.this,name,track);

1 个答案:

答案 0 :(得分:0)

删除内部类,将其作为活动中的一个函数使用。

public void AlertShow()
{
    Context mContext = this;
    LayoutInflater inflater = getLayoutInflater();
    View alertLayout = inflater.inflate(R.layout.layout_custom_dialog, null);
    final EditText name = (EditText) alertLayout.findViewById(R.id.et_name);
    //final EditText track = (EditText) alertLayout.findViewById(R.id.et_track);
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Add track number");
    //alert.setIcon(R.drawable.plus);
    alert.setView(alertLayout);
    alert.setCancelable(false);
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(mContext, "Abort", Toast.LENGTH_SHORT).show();
        }
    });
    alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            String sname = name.getText().toString();
            //String track = etPassword.getText().toString();
            Toast.makeText(mContext, "Name: " + sname +"  "+  " Track: " , Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog dialog = alert.create();
    dialog.show();
}

然后调用它:

AlertShow();