动态更改按钮文本。

时间:2013-07-05 10:43:26

标签: java android

Android的新手并没有花很长时间让我碰壁。我正在制作一个应用程序,有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]);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我想循环应该是

for (int i=buttons.length-1; i>=0; i--){
    buttons[i].setText(randNo[i]);
}