在文本视图中更改文本

时间:2015-11-30 18:43:42

标签: android

我在textview中显示的文本在一段时间后会发生变化。我想在循环中执行此操作,即文本恢复为原始文本然后再次更改。这是代码。

MainActivity.java

\bno_index\b

2 个答案:

答案 0 :(得分:2)

试试这个。

qoutes=(TextView)rootView.findViewById(R.id.textView_q);
int i = 0;

Handler handler = new Handler();
handler.postDelayed(new Runnable(){ 


    @Override
    public void run() {
        // TODO Auto-generated method stub
        if(i%2==0){
          qoutes.setText("I don’t trust words. I trust pictures. – Gilles Peress ");
        }else{
          qoutes.setText("You don’t take a photograph. You ask quietly to borrow it. – Unknown  ");
        }
        i++;
    }
}, 10000);

修改

Timer timer;
TimerTask timertask;
int i = 0;

qoutes=(TextView)rootView.findViewById(R.id.textView_q);
timer = new Timer();
timertask = new TimerTask() {

     @Override
     public void run() {
        runOnUiThread(new Runnable() {

          @Override
          public void run() {
            if(i%2==0){
              qoutes.setText("I don’t trust words. I trust pictures. – Gilles Peress ");
            }else{
              qoutes.setText("You don’t take a photograph. You ask quietly to borrow it. – Unknown  ");
            }
            i++;
          }
      });
   }
};
timer.scheduleAtFixedRate(timertask, 100, 10000);

答案 1 :(得分:1)

首先,创建String资源和成员变量以跟踪显示的当前文本。最好存储在strings.xml中,但是对于这个简单的例子,我们只使用String数组。还要将Handler创建为成员变量。

nltk.word_tokenize

然后,在onCreateView()中:

    TextView qoutes;
    Handler handler = new Handler();
    int currentTextPosition = -1;
    String[] textArray = new String[]{"I don’t trust words. I trust pictures. – Gilles Peress ",
            "You don’t take a photograph. You ask quietly to borrow it. – Unknown  "};

并且,Runnable的定义:

    qoutes=(TextView)rootView.findViewById(R.id.textView_q);
    handler.postDelayed(setTextRunnable, 10000);

这将每隔10秒运行一次,直到你停止它,你可以通过调用:

来完成
Runnable setTextRunnable = new Runnable(){ 
    @Override
    public void run() {
        if (currentTextPosition < 0 ) {
         currentTextPosition = 0;   
        } else {
            currentTextPosition++;
            if (currentTextPosition >= textArray.length) {
                currentTextPosition = 0;
            }
        }
        qoutes.setText(textArray[currentTextPosition]);
        handler.postDelayed(this, 10000);
    }
};