一个按钮响应两个textView

时间:2017-02-28 18:00:57

标签: java android onclick

我的应用需要生成一个随机数并将其设置为TextView,同时通过点击一个按钮从TextView上的倒数计时器设置时间。但是,我无法找到如何使其发挥作用的解决方案。

public class GenerateToken extends ActionBarActivity {

TextView show;
CountDownT timer;

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

    show =(TextView)findViewById(R.id.textView2);
    show.setText("60");
}

 public void generate (View v)
 {
    Random rand = new Random();
    int number = rand.nextInt(1999999999 - 1000000000)+1000000000;
    TextView myText = (TextView)findViewById(R.id.textView);
    String myString = String.valueOf(number);
    myText.setText(myString);
        timer.start();
    }

}
public class CountDownT extends CountDownTimer{

    public CountDownT (long InMillisSeconds, long TimeGap){
        super(InMillisSeconds,TimeGap);
    }

    @Override
    public void onTick(long l){
        show.setText((l/1000) +"");
    }

    @Override
    public void onFinish(){
        show.setText("Request New Token..");
    }
}

2 个答案:

答案 0 :(得分:0)

非常容易。只需在setOnClickListener()上设置Button即可更改TextView。喜欢 -

 button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   textView1.setText("Text changed on TextView 1");
                   textView2.setText("Text changed on TextView2");
                }
            });

答案 1 :(得分:0)

试试这个。我猜你在按钮xml中添加onClick="generate"

public class GenerateToken extends ActionBarActivity {

TextView show;
TextView myText;
CountDownT timer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_generate_token);
    myText = (TextView)findViewById(R.id.textView);
    show =(TextView)findViewById(R.id.textView2);
    show.setText("60");
 }

 public void generate (View v)
 {
    Random rand = new Random();
    int number = rand.nextInt(1999999999 - 1000000000)+1000000000;
    String myString = String.valueOf(number);
    myText.setText(myString);

    new CountDownTimer(30000, 1000) {

       public void onTick(long millisUntilFinished) {
          show.setText(millisUntilFinished / 1000+"");
       }

       public void onFinish() {
          //{code to do after the timer finishes}
       }

    }.start();

 }
}

这里30000是毫秒计数,1000是间隔。所以这里倒计时30秒。根据您的需要改变时间。希望这会有所帮助。