setText到循环不起作用setVisibility也没有

时间:2016-05-15 19:32:32

标签: android

.setText在for循环中不起作用。 并且setVisibility在setAlphabet()结束后才起作用 对不起我的英文...

private ImageButton playTeste1;
private TextView alfabeto;

public void setListeners(){
    playTeste1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            playTeste1.setVisibility(View.INVISIBLE);
            alfabeto.setVisibility(View.VISIBLE);
            setAlphabet();
        }
    });



 public void setAlphabet(){
       try{
           String temp;
           for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) {
            System.out.println(alphabet);
            temp = String.valueOf(alphabet);
            alfabeto.setText(temp);
            Thread.sleep(1000);
        }
        }catch (InterruptedException e) {
               System.out.println("error in Thread");
           }
    }

1 个答案:

答案 0 :(得分:0)

也许问题是你不在UI线程上。在这种情况下,您应该尝试在runOnUIThread方法中设置文本。

public void setAlphabet(){
   try{
       String temp;
       for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) {
        System.out.println(alphabet);
        temp = String.valueOf(alphabet);
        try {
                 // code runs in a thread
                 runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            alfabeto.setText(temp);
                        }
                 });
           } catch (final Exception ex) {
               Log.i("---","Exception in thread");
           }
        Thread.sleep(1000);
    }
    }catch (InterruptedException e) {
           System.out.println("error in Thread");
       }
}

必须在Activity类或Activity对象(或其子类)中调用runOnUIThread方法。