0

安卓新手,没多久我就撞墙了。我正在制作一个应用程序,有 10 个标记为 0-9 的按钮。当按下按钮时,我想随机播放数字。我创建了一个按钮数组和一个字符串数组(0-9)。按钮被转换为列表,打乱,然后发送回数组。它在按下任何按钮时崩溃。

package com.wumble.dialer0845;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView telNo;
//declare buttons to use in code
Button B0,B1,B2,B3,B4,B5,B6,B7,B8,B9;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    telNo=(TextView)findViewById(R.id.telNo);
    telNo.setText("");
    B0=(Button)findViewById(R.id.B0);
    B1=(Button)findViewById(R.id.B1);
    B2=(Button)findViewById(R.id.B2);
    B3=(Button)findViewById(R.id.B3);
    B4=(Button)findViewById(R.id.B4);
    B5=(Button)findViewById(R.id.B5);
    B6=(Button)findViewById(R.id.B6);
    B7=(Button)findViewById(R.id.B7);
    B8=(Button)findViewById(R.id.B8);
    B9=(Button)findViewById(R.id.B9);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public void butt_Pressed(View sender){
    //get button that is pressed
    Button butt=(Button)sender;
    //append new number
    telNo.append(butt.getText());
    //shuffle buttons
    buttonArray();
}

public void buttonArray(){
    String randNo[]={"0","1","2","3","4","5","6","7","8","9"};
    Button buttons[]={B0,B1,B2,B3,B4,B5,B6,B7,B8,B9};
    //convert array to list > shuffle >back to array
    List<String> randList = Arrays.asList(randNo);
    Collections.shuffle(randList);
    randList.toArray(randNo);
    //assign text to buttons
        for (int i=buttons.length; i>=0; i--){
            buttons[i].setText(randNo[i]);
        }
    }
}
4

1 回答 1

1

我猜for循环应该是

for (int i=buttons.length-1; i>=0; i--){
    buttons[i].setText(randNo[i]);
}
于 2013-07-05T10:48:43.697 回答