如何正确使用setOnItemClickListener? [英] How do I properly use an setOnItemClickListener?

查看:128
本文介绍了如何正确使用setOnItemClickListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们从Android的新手开始.

Lets start with new to android I am.

我有一个GridView设置作为网格,我用它来代表我正在制作的一个小型棋盘游戏应用程序的棋盘.我已经为我的GridView设置了一个"setOnItemClickListener",该功能至少对于Toast起作用,并且设置了我放入那里进行测试的ImageResource.

I have a GridView setup as a grid and I'm using it to represent a board for a little board game app that I'm making. I have setup a "setOnItemClickListener" for my GridView that functions, at least for the Toast and set ImageResource I put in there for a test.

我不知道如何从ClickListener的其他类中调用我的方法来控制触摸发生时发生的情况.似乎没有名称或其他可与其他方法结合使用的东西. 当我尝试将代码放入setOnItemClickListener时,我得到一条警告,说我要从中调用方法的类的Object必须是最终的,才能在另一个方法的内部类中使用.

I don't know how to call my methods from other classes inside of the ClickListener to control what happens when touches occur. There doesn't appear to be a name or anything to use in conjunction with other methods. When I try to put my code inside the setOnItemClickListener but I get a warning saying that my Object, of the class I want to call the methods from, must be final to use in the inner class of another method.

我无法将对象更改为final,因此我需要一种方法来运行一个小的游戏循环,该循环将通过与该setOnItemClickListener进行通信来调用我需要的其他类的对象上的所有方法.

I can't change my objects to final so I need a way to run a little game loop that will be calling all the methods on objects from other classes that I require by communicating with that setOnItemClickListener.

这是我的代码中具有侦听器的部分:

Here is the part of my code that has the Listener:

public View play(GridView gv) { 
    boolean p1turn = true;
    while (gameOver == false) {
        gv.setOnItemClickListener(new OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View v, int position, long id){
                Toast.makeText(ctxt, "" + position, Toast.LENGTH_SHORT).show();
                ImageView img = (ImageView)v;
                img.setImageResource(R.drawable.paper1select);
            }
        });
        System.out.println("Why no get here??");
        return(gv);//IDK why but this is NEVER reached, almost like the oICL is an infinite loop???
    }
    return gv;
}

侦听器中的Toast和两条ImageView img行仅用于测试以查看它是否可以工作并且可以完成这些任务. 尽管如此,我需要一种在代码其他位置使用监听器的方法.

The Toast and two ImageView img lines inside the listener are only for testing to see if it would work and it does for those task. I need a way to use the Listener in other places of my code though.

例如,在第一次触摸时,我想调用一个我创建的方法,该方法将确定所选项目是否为可移动的合格单位,如果是,则将该位置的图像替换为新图像.所以看起来就像我想像的那样-gv.onTouchEvent1.checkPiece(player1,position); -checkPiece将在ClickListener中获得位置并执行其功能.

For an example, on the first touch, I would like to call a method I have created that will determine if the item selected is an eligible unit to move, and if so swap the image at that position with a new image. So it would look something like this I would imagine - gv.onTouchEvent1.checkPiece(player1, position); - Where checkPiece will get position from the ClickListener and perform it's function.

任何setOnItemClickListener教程建议都很好.

Any setOnItemClickListener tutorial suggestions would be nice.

----------------使用我的解决方案进行编辑--------------------------- -----

----------------EDIT WITH MY SOLUTION--------------------------------

我唯一能使它工作的方法是在onItemClick...中使用一个计数器,该计数器使我能够根据使用if语句和循环的计数来控制调用哪个方法.这项工作仍在进行中,因此会有一些垃圾,稍后我会删除,但这基本上表明了我所需要的:

The only way I was able to make it work was by using a counter inside the onItemClick... that would allow me to control which method was called depending on what count was on using if statements along with a loop. This is still a work in progress so has some junk that I will delete later on, but this shows basically what I needed:

public class MainActivity extends Activity {

/*
 * count used to keep track of which step of game-play we are on. pNum used
 * to track which player's turn it is.
 */
protected static int count = 0, pNum = 0, round = 0;

// Used to keep know that a step is done, in conjunction with count,
// redundant I believe. TRUE indicates "done".
protected static boolean choosePiece = false, chooseEmpty = false,
        verifyEmpty = false, selectEnemy = false, verifyEnemy = false;

// Used to track selected piece location.
protected static int selectedLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageAdapter iA = new ImageAdapter(this);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(iA);

    final GameplayController gc = new GameplayController(this);

    // Create board model, add units to player's list.
    final UnitArray gameBoardModel = new UnitArray();

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            while (count <= 6) {
                System.out.println("While loop cycle: " + round);
                /*
                 * First IF is for selecting piece to move.
                 */
                if (count == 0) {
                    System.out.println("IF 0 WAS HIT");
                    System.out.println("It is player " + pNum
                            + "s turn, round " + round);
                    choosePiece = gc.choosePiece(position, gameBoardModel,
                            (ImageView) v, pNum);
                    if (choosePiece == true) {
                        count++;
                    }
                    selectedLocation = position;
                    break;
                }
                /*
                 * Second IF is for selecting blank space to move to.
                 */
                if (count == 1 && choosePiece == true
                        && chooseEmpty == false) {
                    System.out.println("IF 1 WAS HIT");
                    chooseEmpty = gc.chooseEmpty(position, gameBoardModel,
                            (ImageView) v);
                    if (chooseEmpty == true) {
                        count++;
                    }
                    break;
                }
                /*
                 * Third IF is for verifying the blank selected and moving
                 * piece.
                 */
                if (count == 2 && verifyEmpty == false
                        && choosePiece == true && chooseEmpty == true) {
                    System.out.println("IF 2 WAS HIT");
                    verifyEmpty = gc.checkEmptyChoice(position);
                    if (verifyEmpty == true) {
                        gc.moveToEmpty(position, gameBoardModel,
                                (ImageView) v, selectedLocation);
                        count++;
                        iA.notifyDataSetChanged();
                        selectedLocation = position;
                    }
                    break;
                }
                /*
                 * Fourth IF is for selecting an enemy unit to attack.
                 */
                if (count == 3 && selectEnemy == false
                        && verifyEmpty == true && choosePiece == true
                        && chooseEmpty == true) {
                    System.out.println("IF 3 WAS HIT");
                    selectEnemy = gc.selectEnemy(position, gameBoardModel,
                            (ImageView) v);
                    if (selectEnemy == true) {
                        count++;
                    }
                    break;
                }

                /*
                 * Fifth IF is for verifying enemy unit to attack and then
                 * attacking.
                 */
                if (count == 4 && verifyEnemy == false
                        && selectEnemy == true && verifyEmpty == true
                        && choosePiece == true && chooseEmpty == true) {
                    System.out.println("IF 4 WAS HIT");
                    verifyEnemy = gc.verifyEnemySelected(position);
                    if (verifyEnemy) {
                        /*
                         * For clarity, position is enemy being attacked,
                         * selectedLocation is position of attacking unit.
                         */
                        gc.attackEnemy(position, gameBoardModel,
                                (ImageView) v, selectedLocation);

                        // RESET FOR NEXT PLAYER TURN.
                        iA.notifyDataSetChanged();
                        if (pNum == 0) {
                            pNum = 1;
                        } else {
                            pNum = 0;
                        }
                        iA.notifyDataSetChanged();
                        count = 0;
                        choosePiece = false;
                        chooseEmpty = false;
                        verifyEmpty = false;
                        selectEnemy = false;
                        verifyEnemy = false;
                        round++;
                    }
                    break;
                }
            }
        }
    });
}
...

onItemClick中包含如此多的代码对我来说似乎很奇怪.我最初的意图是调用一种方法,该方法几乎包含了最终放入onClick中的所有内容,因为我无法弄清楚如何仅凭其位置来区分触摸事件.

It just seems strange to me to have so much code going on in the onItemClick. My original intention was to call a method that pretty much contained everything that I ended up putting in the onClick, since I couldn't figure out how to differentiate touch events on their location alone.

推荐答案

我不会称自己为新人

I wouldn't call myself a newcomer

嗯...

当我尝试将代码放入setOnItemClickListener时,我收到一条警告,说我的对象(要从中调用方法的类)必须是最终对象才能在另一个方法的内部类中使用.

When I try to put my code inside the setOnItemClickListener but I get a warning saying that my Object, of the class I want to call the methods from, must be final to use in the inner class of another method.

这是因为所讨论的对象不是setOnItemClickListener()的参数,还是局部变量,而不是play()方法所在类的数据成员.

That is because the objects in question are either parameters to setOnItemClickListener() or are local variables, as opposed to being data members of the class where your play() method resides.

请记住,OnItemClickListener是一个接口,因此您不需要像现在那样使用匿名内部类.例如,您可以在(可能是)托管play()方法的Activity上实现此接口.

Bear in mind that OnItemClickListener is an interface, and so you do not need to use an anonymous inner class as you presently are. For example, you could implement this interface on the Activity that (presumably) is hosting the play() method.

匿名内部类是一种强大而又熟练的Java技术.我教过许多Android课程,并且有很多经验丰富的Java开发人员不认识匿名的内部类,更不用说使用匿名的内部类了.考虑到您的相对经验水平,我建议您尽可能避免使用它们.

Anonymous inner classes are a powerful, but expert, Java technique. I have taught many Android courses, and there are lots of experienced Java developers who do not recognize, let alone use, anonymous inner classes. Given your relative experience level, I would recommend that you avoid their use for the time being wherever possible.

这是我的代码中具有侦听器的部分

Here is the part of my code that has the Listener

您正在循环调用setOnItemClickListener().这可能不是您想要的.

You are calling setOnItemClickListener() in a loop. This is probably not what you want.

不过,我需要一种在代码其他位置使用监听器的方法.

I need a way to use the Listener in other places of my code though.

不,你不知道.您可能需要让侦听器通过其onItemClick()方法执行其他操作,但是侦听器本身(仅作为对象)将仅在此位置使用,除非出现一些严重奇怪的编码.

No, you don't. You may need to have the listener do other things from its onItemClick() method, but the listener itself, as an object, is only going to be used in this one place, barring some seriously strange coding.

所以我会想到这样的样子-gv.onTouchEvent1.checkPiece(player1,position); -

So it would look something like this I would imagine - gv.onTouchEvent1.checkPiece(player1, position); -

或者在Activity上实现checkPiece(),该c9(大概)托管了所有这些代码,在这种情况下,您只需调用它即可.

Or implement checkPiece() on the Activity that is (presumably) hosting all of this code, in which case you just call it.

我已经学习Java一年了,我的第一门语言

I have been learning Java for a year now, my first language

直言不讳,您的问题与Android无关,而与Java无关.可以在StackOverflow上随意询问Java语法和相关问题,但是可以使用标记),如果它与Java的相关性更高,而与Android的类和方法的相关性更小.

To be completely blunt, your problems have little to do with Android and everything to do with Java. Feel free to ask java syntax and related questions here on StackOverflow, but do so with the tag) if it is likely to be related more to Java and less regarding Android's classes and methods.

这篇关于如何正确使用setOnItemClickListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆