我是 Android 新手。
我需要为 Activity 创建某种预加载器。现在,我单击“显示公司”按钮,然后我进入下一个 Activity ,其中数据从服务器加载并显示在内部。问题是(据我了解)该 Activity 正在与互联网连接,并且在连接完成之前没有任何显示。用户必须等待,然后突然(几秒钟后 - 变化)他会根据新 Activity 获得新的 100% 就绪页面。
对我来说最好的办法是:创建一个加载动画,直到 Activity 完全加载为止。 (这可以解决所有问题)
替代方案是:在连接互联网网址之前加载新 Activity 。加载时,它会默认显示“正在加载数据”,直到从 url 下载全文,该文本将替换第一个文本。
这是我用来从 URL 加载文本的代码。
try {
// Create a URL for the desired page
URL url = new URL(serwer_url);
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
Plain_str = Plain_str + str;
}
Log.i("Plain read str", Plain_str);
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {}
//end of reading file
//here is the anchor to the text in activity
TextView MainText = (TextView)findViewById(R.id.TextMain);
MainText.setText(Html.fromHtml(Plain_str.toString()));
最佳答案
您可以像这样使用 AsyncTask:
protected class Mytask extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
String Plain_str= null;
try {
// Create a URL for the desired page
URL url = new URL(serwer_url);
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
Plain_str = Plain_str + str;
}
Log.i("Plain read str", Plain_str);
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {}
return Plain_str;
}
protected void onPostExecute(String str){
TextView MainText = (TextView)findViewById(R.id.TextMain);
MainText.setText(Html.fromHtml(str.toString()));
}
}
然后执行任务
new MyTask().execute();
关于java - Activity 之间的预加载器 - android java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13251168/