本文介绍了从onclicklistener访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个onItemLongClickListener的列表视图,获取一个参数'廉政位置在,里面过去了,我已经有两个按钮的alertDialogBu​​ilder。我还有另一个onclickListener的按钮。我需要从第二个侦听器中访问的位置。反正有没有做到这一点,而不使其成为一个全球性的?

So I have an onItemLongClickListener for a list view that gets a parameter 'int position' passed in. Inside, I have an alertDialogBuilder which has two buttons. I have another onclickListener for the buttons. I need to access the position from inside the second listener. Is there anyway to do this without making it a global?


public boolean onItemLongClick(AdapterView parent, View itemView, int position, long id){

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BookFace.this);
    alertDialogBuilder.setTitle("Choose an option.");
    alertDialogBuilder
    .setMessage("What would you like to do?")
    .setCancelable(true)
    .setPositiveButton("Edit", new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent();
            intent.putExtra("position", position); //Can't access this variable
            intent.setClass(SomeClass.this, EditActivity.class);
            startActivity(intent);
    }

感谢您的帮助。

Thanks for your help.

推荐答案

在Java中,你只有当他们被第一个声明为最后。所以,你可以添加:

In Java, you can access outer variables from an inner class declaration only if they are first declared as final. So you could add:

final int selectedPosition = position;

要你的方法的顶部,并使用该值在你的额外,即

to the top of your method and use that value in your extra, i.e.

intent.putExtra("position", selectedPosition);

这篇关于从onclicklistener访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 20:14