显示ProgressDialog Android


78

我有一个EditText,它从用户和一个searchButton中获取一个字符串。单击searchButton时,它将搜索XML文件并将其显示在ListView中。

我能够从用户那里获取输入,搜索XML文件并在ListView中也显示usersearched值。

我想要的是ProgressDialog在单击searchButton之后显示一个“请等待...正在检索数据...”之类的信息,然后在显示数据时将其关闭。

public class Tab1Activity extends ListActivity {
private Button okButton;
private Button searchButton;
Toast toast;
String xml;

private TextView searchText;
private String searchTextString;
HashMap<String, String> o;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab1);

    searchButton = (Button) findViewById(R.id.search_button);
    searchButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            System.out.print("hello");

            searchText = (TextView) findViewById(R.id.search_text);
            searchTextString = searchText.getText().toString();
            readXml(searchTextString);

        }
    });

}

private void readXml(String searchTextString1) {
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

    String xml = XMLfunctions.getXML();
            //Here XMLfunctions is class name which parse xml
    Document doc = XMLfunctions.XMLfromString(xml);

    int numResults = XMLfunctions.numResults(doc);

    if ((numResults <= 0)) {
        Toast.makeText(Tab1Activity.this, "Testing xmlparser",
                Toast.LENGTH_LONG).show();
        finish();
    }

    NodeList nodes = doc.getElementsByTagName("result");

    for (int i = 0; i < nodes.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();

        Element e = (Element) nodes.item(i);
        String nameMapString = XMLfunctions.getValue(e, "name");



         if ( nameMapString.toLowerCase().indexOf(searchTextString1.toLowerCase()) != -1 )   // != -1 means string is present in the search string
            {
                map.put("id", XMLfunctions.getValue(e, "id"));
                map.put("name",  XMLfunctions.getValue(e, "name"));
                map.put("Score",  XMLfunctions.getValue(e, "score"));
                mylist.add(map);
            }
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist,
            R.layout.parsexml, new String[] { "name", "Score" }, new int[] {
                    R.id.item_title, R.id.item_subtitle });

    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv
                    .getItemAtPosition(position);


                Toast.makeText(Tab1Activity.this,
                         "Name "+o.get("name")+"  Clicked", Toast.LENGTH_LONG)
                        .show();                

        }
    });
}


2
它说:“在活动内部使用进度指示器,例如ProgressBar,而不是使用此模式对话框。” 他们为什么不简单地向我们展示如何做呢?:)
Wolf359

Answers:


265

声明您的进度对话框:

ProgressDialog progress;

准备开始进度对话框时:

progress = ProgressDialog.show(this, "dialog title",
    "dialog message", true);

并在完成后使其消失:

progress.dismiss();

这是一个适合您的线程示例:

// Note: declare ProgressDialog progress as a field in your class.

progress = ProgressDialog.show(this, "dialog title",
  "dialog message", true);

new Thread(new Runnable() {
  @Override
  public void run()
  {
    // do the thing that takes a long time

    runOnUiThread(new Runnable() {
      @Override
      public void run()
      {
        progress.dismiss();
      }
    });
  }
}).start();

我已经写了下面的代码,但不起作用:'searchButton.setOnClickListener(new View.OnClickListener(){public void onClick(View v){// TODO自动生成的方法存根System.out.print(“ hello”); searchText = (TextView)findViewById(R.id.search_text); searchTextString = searchText.getText()。toString(); progress.show(Tab1Activity.this,“对话框标题”,“请稍候...正在加载”); readXml(searchTextString ); progress.dismiss();}});'
captaindroid 2012年

nup,它花费的时间非常小,如您在上面看到的,我也编写了readXML方法。
captaindroid 2012年

我想知道readXML是否运行得如此之快,以至于看不到进度对话框。如果您实际上是在网络上花费了几秒钟的时间-首先,您可以在单独的线程中执行此操作,但是随后您会看到进度对话框的全部效果。如果最终添加线程,请确保您showdismissUI线程中的进度对话框。
dldnh 2012年

但是我认为它有足够的时间来显示progressDialog。当我单击searchButton时,大约需要2-3秒。
captaindroid 2012年

您知道吗,可能是因为readXML不允许UI屏住呼吸。您可能希望将其放在自己的线程中-可以按Win Myo Htet的建议使用简单new Thread(...)(我更喜欢)或使用AsyncTask
dldnh 2012年

7

我正在从互联网上下载数据的当前项目之一中使用以下代码。一切都在我的活动课内。

// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... urls) {
        try {
            String xmlUrl = urls[0];

            URL u = new URL(xmlUrl);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int lengthOfFile = c.getContentLength();

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; // total = total + len1
                publishProgress("" + (int) ((total * 100) / lengthOfFile));
                xmlContent += buffer;
            }
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        Log.d("ANDRO_ASYNC", progress[0]);
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Retrieving latest announcements...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }

}

方向改变对我来说很好。我刚刚在2.3.3 AVD和ICS手机上进行了测试。
the_gesslar 2012年

我该如何执行呢?
user1708134'3

6

在为进度栏创建对象时,请检查以下内容。

这将失败:

dialog = new ProgressDialog(getApplicationContext());

在添加活动时,上下文起作用。

dialog = new ProgressDialog(MainActivity.this);


1

我正在从互联网上下载数据的当前项目之一中使用以下代码。一切都在我的活动课内。

private class GetData extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = ProgressDialog.show(Calendar.this,
                    "", "");

        }

        @Override
        protected JSONObject doInBackground(String... params) {

            String response;

            try {

                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost(url);

                HttpResponse responce = httpclient.execute(httppost);

                HttpEntity httpEntity = responce.getEntity();

                response = EntityUtils.toString(httpEntity);

                Log.d("response is", response);

                return new JSONObject(response);

            } catch (Exception ex) {

                ex.printStackTrace();

            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) 
        {
            super.onPostExecute(result);

            progressDialog.dismiss();

            if(result != null)
            {
                try
                {
                    JSONObject jobj = result.getJSONObject("result");

                    String status = jobj.getString("status");

                    if(status.equals("true"))
                    {
                        JSONArray array = jobj.getJSONArray("data");

                        for(int x = 0; x < array.length(); x++)
                        {
                            HashMap<String, String> map = new HashMap<String, String>();

                            map.put("name", array.getJSONObject(x).getString("name"));

                            map.put("date", array.getJSONObject(x).getString("date"));

                            map.put("description", array.getJSONObject(x).getString("description"));

                            list.add(map);
                        }

                        CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);

                        list_of_calendar.setAdapter(adapter);
                    }
                }
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }
            else
            {
                Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
            }
        }

    }

并在OnCreate方法中执行它 new GetData().execute();

其中Calendar是我的calendarActivity,我还创建了CalendarAdapter来将这些值设置为列表视图。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.