我已经在Android上取得了进度条,但它根本不起作用。我究竟做错了什么?我刚刚开始学习android。以下是我的代码。
MainActivity.java -
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int mporgress=0;
EditText time;
private Handler mHandler = new Handler();
private static final int PROGRESS = 0x1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Startbuttononclick(View view){
Button startbutton=(Button) findViewById(R.id.button);
startbutton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mporgress = Integer.parseInt(time.getText().toString());
progressBar.setProgress(mporgress);
new Thread(new Runnable() {
public void run() {
while (mporgress < 100) {
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(mporgress);
mporgress = doWork();
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
}
});
}
}
}).start();
}
});
}
public void doprogress(View view) {
}
public int doWork(){
mporgress++;
return mporgress;
}
}
activity_main.xml中 -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android.progressbar.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the time:"
android:inputType="number"
android:id="@+id/editText" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="500dp"
android:layout_height="200dp"
android:id="@+id/progressBar4"
android:layout_gravity="center"
android:scrollbarSize="500dp" />
<Button
android:text="START"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_gravity="center"
android:onClick="Startbuttononclick" />
</LinearLayout>
请看下面的图片 - - https://i.stack.imgur.com/2TBIb.png
注意 - 输入此图像中的时间是带有提示而不是TextView的EditText。
出现但不起作用。
到目前为止,我已完成了这些更改.- https://i.stack.imgur.com/UujpB.png
但进度条仍在不断旋转。
答案 0 :(得分:0)
似乎您忘记初始化EditText -time
和ProgressBar
。在onCreate
内启动它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar =(ProgressBar) findViewById(R.id.progressBar4);
time = (EditText) findViewById(R.id.editText); //here
}
同样在内部按钮中,点击bar
:
progressBar = new ProgressBar(this);
mporgress = Integer.parseInt(time.getText().toString());
................
.............