我想要水平进度条从0移到100。我在布局中添加了此代码。我应该如何移动此进度栏?
<ProgressBar
android:id="@+id/progressBar"
android:indeterminate="false"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:progress="0"
android:max="100"
style="@android:style/Widget.ProgressBar.Horizontal"
/>
试试这个代码:
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btn;
private ProgressBar progressBar;
TextView txt;
Integer count =1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
btn = (Button) findViewById(R.id.btn);
btn.setText("Start");
txt = (TextView) findViewById(R.id.output);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
count =1;
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
new MyTask().execute(100);
});
}
class MyTask extends AsyncTask<Integer, Integer, String> {
@Override
protected String doInBackground(Integer... params) {
for (count=1 ; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
@Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
txt.setText(result);
btn.setText("Restart");
}
@Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
@Override
protected void onProgressUpdate(Integer... values) {
txt.setText("Running..."+ values[0]);
progressBar.setProgress(values[0]);
}
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。