开发者

Android Dialog cannot 'see' final / global variable

开发者 https://www.devze.com 2023-03-31 13:52 出处:网络
I have an AlertDialog, which for some strange reason cannot access a final int deptID. When passing the value to the ConfirmRemoval-function, the value is correct, but when I enter the dialog\'s onCli

I have an AlertDialog, which for some strange reason cannot access a final int deptID. When passing the value to the ConfirmRemoval-function, the value is correct, but when I enter the dialog's onClick event, the final int is undefined!

I have even tried to change this to a global variable, but still no luck. Anybody know what is going on?

@Override
public void onCreate(Bundle icicle){
    super.onCreate(icicle);

    this.setContentView(R.layout.generic_list);
    Bundle extras = getIntent().getExtras();
    if (extras == null) {return;}
    this.getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> adv, View v,
                int pos, long id) {
            Cursor cursor = (Cursor)adv.getItemAtPosition(pos);
            int deptID = cursor.getInt(cursor.getColumnIndex("DeptID"));
            ConfirmRemoval(deptID);
            return true; //NOTE! If returning false, the itemClick event will fire
        }
    });
}

private void ConfirmRemoval(final int deptID){
        AlertDialog.Builder bld = new AlertDialog.Builder(this);
        bld.setCancelable(false);
        bld.setTitle(R.string.deptRemove);
        bld.setMessage(R.string.de开发者_如何学编程ptRemoveMsg);
        bld.setPositiveButton("OK", new AlertDialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                Dept.RemoveDept(deptID);
                dialog.dismiss();
                GetDepartments();
            }


        });
        bld.setNegativeButton("Cancel", new AlertDialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        AlertDialog alert = bld.create();
        alert.show();
}

Thanks, Runey


Ok, you have to write your own OnClickListener - something like:

public static class processAlert implements DialogInterface.OnClickListener {
    int deptID;
    processAlert(int _id){
        deptID = _id;
    }
    public void onClick(DialogInterface dialog, int which) {
         Dept.RemoveDept(deptID);
            dialog.dismiss();
            GetDepartments();   
    }
}

and when you create your dialog

bld.setPositiveButton("OK",new processAlert(deptID))


Instead of

Dept.RemoveDept(deptID) do

int deptIDlocal = deptID; Dept.RemoveDept(deptIDlocal)


try

 final int deptID = cursor.getInt(cursor.getColumnIndex("DeptID"));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号