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

时间:2015-11-18 23:59:58

标签: java android android-fragments

我有Fragment从网站加载数据并显示它们

所以基本上根视图基于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...

1 个答案:

答案 0 :(得分:0)

如果我理解您的问题,那么您希望在进度条中显示进度。 首先,在布局中添加进度条或以编程方式添加(也带有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),否则这将是不好的做法,它可能会停止用户交互,因为主要/ UI线程已经被凝结。

以下是您要实现的good example项内容。