我想简单地制作这段代码 我有一个按钮 但当我点击那个按钮,我想要一个计时器启动.. 并且每个计时器都会在main.xml中创建一个按钮。我可以这样做吗? 请帮帮我先生!
Button a = (Button) findViewById(R.id.button1);
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CountDownTimer(5000,1000) {
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
//how to create a button here!
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
}
}.start();
}
});
我试试这个...但是当我点击按钮时出现这个词(“不幸的是程序已被停止”)
final int i=1;
Button a = (Button) findViewById(R.id.button1);
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CountDownTimer(5000,1000) {
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
//how to create a button here!
LinearLayout linearLayout = (LinearLayout) findViewById(R.layout.main);
Button btn = new Button(NyaActivity.this);
btn.setId(i+1);
linearLayout.addView(btn);
btn.setText("Button"+(i+1));
final int index = i;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("TAG", "The index is" + index);
}
});
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
}
}.start();
}
});
}
答案 0 :(得分:0)
尝试这种方式,在CountDownTimer onTick上动态添加按钮:
int i=1;
Button a = (Button) findViewById(R.id.button1);
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CountDownTimer(5000,1000) {
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
//how to create a button here!
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mainlauoutid);
Button btn = new Button(Your_Current_Activity.this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
btn.setLayoutParams(lprams);
final int index = i;
btn.setOnClickListener(new OnClickListener() {
void onClick(View v) {
Log.i("TAG", "The index is" + index);
}
});
linearLayout.addView(btn);
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
}
}.start();
}
});
,您的布局如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mainlauoutid"
android:orientation="vertical" >
.....
答案 1 :(得分:0)
在main.xml中创建LinearLayout并使用以下命令在a.setOnClickListener之前找到它:
final LinearLayout layout = (LinearLayout) findViewById(R.id.layoutId);
然后在onTick()中调用:
Button newBtn = new Button(YourActivity.this);
newBtn.setText("new button");
layout.addView(newBtn);