【问题标题】:Android - passing array through onClickAndroid - 通过 onClick 传递数组
【发布时间】:2016-04-28 22:28:43
【问题描述】:

作为我尝试创建记忆游戏的一部分,我在布局上放置了 12 个图像按钮,ID 名称为 imageButton1...imageButton12。我编写了一个算法来创建一个名为cards[12] 的数组,它使用随机值来表示每个imageButton 后面的卡片(card1..card6),例如,如果cards[5]=4,那么imageButton6 后面的卡片就是card4。 现在,我试图告诉程序在使用数组单击 imageButton 时显示适当的卡片。我对 android studio 很陌生,据我所知,我首先需要在所有按钮上使用 OnClickListener,所以我使用循环完成了它。到目前为止,这是我的代码:

public class Memory extends AppCompatActivity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_memory);

        int i;
        int[] cards = new int[12];
        // Algorithm here
        for(i=1;i<=12;i++) {
            String name = "imageButton" + i;
            int resID = getResources().getIdentifier(name, "id", "com.amir.supermemory");
            ImageButton btn = (ImageButton) findViewById(resID);
            btn.setOnClickListener(this);
        }

现在是 onClick 函数,它执行点击时切换相应图像的动作。问题是我无法将之前创建的数组cards[]传递给函数(它说“无法解析符号'cards'”),我该怎么做?

public void onClick(View v) {
            switch (v.getId()) {
                case R.id.imageButton1:
                    ImageButton b = (ImageButton) findViewById(R.id.imageButton1);
                    String name = "card" + cards[0]; //cards is shown in red
                    int resID = getResources().getIdentifier(name, "drawable", "com.amir.supermemory");
                    b.setImageResource(resID);
                    break;
                //copy paste forr all imageButtons
            }
        }

感谢您的帮助,谢谢!

【问题讨论】:

    标签: android


    【解决方案1】:

    因为您是在 OnCreate() 本地声明您的卡片数组,所以您无法通过其他方法访问它。

    您需要做的就是全局声明您的卡片数组。

    public class Memory extends AppCompatActivity implements OnClickListener{
    
        int[] cards;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
        int i;
        cards = new int[12];
        ...
    }
    

    【讨论】:

    • 这很简单 :) 现在运行良好,非常感谢!
    【解决方案2】:

    您已在 onCreate 方法中将cards[] 声明为局部变量。请在外面声明并尝试。

    public class Memory extends AppCompatActivity implements OnClickListener{
    int[] cards = new int[12];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_memory);
    
        int i;
                // Algorithm here
        for(i=1;i<=12;i++) {
            String name = "imageButton" + i;
            int resID = getResources().getIdentifier(name, "id", "com.amir.supermemory");
            ImageButton btn = (ImageButton) findViewById(resID);
            btn.setOnClickListener(this);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      相关资源
      最近更新 更多