我编写了一个秒表,但它适用于java,但不适用于Android。如果按下按钮它什么也没做。可能是,Eclipse安装错了吗?
package com.example.stoppuhr;
import java.text.SimpleDateFormat;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
long start;
long millis;
public void onClick(View v) {
Button start1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
TextView textView1 = (TextView)findViewById(R.id.textView1);
start1.setOnClickListener(this);
我认为这是问题。
if (v.getId() == start1.getId()){
textView1.setText("moldu");
start = System.currentTimeMillis();
while (true){
millis = System.currentTimeMillis()-start;
SimpleDateFormat sdfDate = new SimpleDateFormat("mm:ss.SSS");//dd/MM/yyyy
String ausgeben = sdfDate.format(millis);
textView1.setText(ausgeben);
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
感谢您的帮助
答案 0 :(得分:3)
在onCreate
Button start1,button2
TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
textView1 = (TextView)findViewById(R.id.textView1);
start1.setOnClickListener(this);
}
你也在ui线程上调用Thread.sleep(30)
。这将阻止ui线程。
http://developer.android.com/training/articles/perf-anr.html
从文档引用
如果您实施Thread
或HandlerThread
,请确保您的UI线程在等待工作线程完成时不会阻止 - 不要调用 {{1} }或Thread.wait()
。
确保不要在ui主题上调用Thread.sleep()
。
我建议你看看倒数计时器。
Thread.sleep()
//以毫秒为单位
在API级别1中添加导致发送此消息的线程 睡眠给定的时间间隔(以毫秒为单位)。该 不保证精度 - 线程可能睡眠多于或少于 请求。
参数time睡眠时间(以毫秒为单位)。抛出 如果为此Thread调用了interrupt(),则InterruptedException 它正在睡觉参见中断()
答案 1 :(得分:3)
public void onClick(View v) {
单击按钮时应该调用的方法,但是必须为您的按钮注册一个OnClickListener类。您尝试在onClick
内执行此操作。
所以你的类(MainActivity
)永远不会被注册为OnClickListener。试试这个:
Button start1 = (Button)findViewById(R.id.button1);
start1.setOnClickListener(this);
到onCreate
。
答案 2 :(得分:0)
您需要做的第一件事:addOnClickListener()
,您可以阅读它。我会谷歌了解它是如何工作的。
如果您将此添加到按钮,请使用
Button buttonname = (Button) findViewById(R.id.yourbuttonid);
buttonname.setOnClickListener(this);
在您的onCreate()
方法中,您已成功将onClickListener()
添加到按钮。
如果现在按下此按钮,则会调用onClick()
。