Android:用用户输入填充水平进度条



好的,所以我的程序应该帮助用户跟踪他们在任何特定任务中取得的进展。

它有一个<EditText>视图,将要求用户输入一个数字,该程序有一个OnClickListener(),一旦用户单击按钮添加数字输入,它将激活一系列代码。

该序列将此输入转换为字符串,然后转换为 int。int 被添加到状态栏的进度中(仅用作其进度的图形表示)。

我在 Netbeans 上没有收到任何错误,而且我编写的内容似乎在直觉上没有任何错误,但是每次我尝试运行它时,应用程序都会崩溃。这是我第一次尝试进度条,所以我可能只是错过了一些我没有看到的东西。感谢您能够提供的任何帮助!我真的很感激!

package com.example.progresstracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
    Button add;
    ProgressBar mProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProgress.setProgress(0);
        mProgress.setMax(100);
        add = (Button) findViewById(R.id.bAdd);
        mProgress = (ProgressBar) findViewById(R.id.prog);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 EditText eText = (EditText) findViewById(R.id.edit);
                 String message = eText.getText().toString();
                 int num = Integer.parseInt(message);

                 mProgress.incrementProgressBy(num);

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

尝试放置此行

mProgress = (ProgressBar) findViewById(R.id.prog);

在此行之前

mProgress.setProgress(0);

您需要先初始化 mProgress,然后才能开始调用其方法。

附言如果您遇到错误,在代码旁边包含堆栈跟踪总是很有用的。

最新更新