繁体   English   中英

在加载数据并返回视图时显示ProgressDialog

[英]Show ProgressDialog while loading data and return view

我有片段,可以从Web加载数据并显示它们

因此,根视图基本上是基于Web数据的,只有在加载数据后才能显示

所以我想做的是在加载数据时显示ProgressDialog

我的代码:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    URL url = null;
    InputStream is = null;
    HttpURLConnection urlConn = null;
    int responseCode = 0;
    try {
        View rootView = inflater.inflate(R.layout.todo, container, false);
        rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        url = new URL(getString(R.string.url)+"/todo.php");
        urlConn = (HttpURLConnection) url.openConnection();
        // ADD DATA TO ROOT VIEW
        }
        return rootView;
    }catch...

如果我正确理解了您的问题,那么您想在进度栏中显示进度。 首先,将进度条添加到布局中,或以编程方式添加进度条(以及ID)。 然后通过findViewById在代码中找到它。

现在您基本上可以做到:

try {
        ProgressBar pb = new ProgressBar(this); // findViewById instead!
        HttpURLConnection urlConnection = (HttpURLConnection) new URL("www.google.com").openConnection();
        urlConnection.connect();
        InputStream is = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str;
        while ((str = br.readLine()) != null) {
            // here you can set an indeterminate progress bar for example
            pb.setIndeterminate(true);
            Log.d("log", str);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

但是您应该考虑在后台执行此操作(例如,使用AsyncTask),因为否则这将是一种不好的做法,并且由于Main / UI线程已被阻塞,因此它可能会使用户交互停止。

这是您要实现的目标的一个很好的例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM