我正在进行延迟加载,几乎完成了它。但是想用它来实现一个进度对话框,因为在开始活动和完成显示内容之间大约需要10秒。一旦我点击一个按钮开始,它就会停留在当前页面(Main.java)大约4秒钟,然后再转到下一页(Activity.java)。然后显示内容大约需要2-4秒。
尝试了这里和网上可用的示例,但它们运行不正常(能够显示对话框,但在内容全部下载后无法正确解除)。
问题是,一旦用户点击按钮,我该如何立即实施进度指示器?
Activity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings, dStrings );
list.setAdapter(adapter);
}
private String[] mStrings = {};
private String[] dStrings = {};
public Activity()
{
String imageC = "";
String textC = "";
try {
// Get the URL from text box and make the URL object
URL url = new URL(targetURL);
// Make the connection
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = reader.readLine();
Pattern sChar = Pattern.compile("&.*?;");
Matcher msChar = sChar.matcher(line);
while (msChar.find()) line = msChar.replaceAll("");
while (line != null) {
if(line.contains("../../"))
{
int startIndex = line.indexOf("../../") + 6;
int endIndex = line.indexOf(">", startIndex + 1);
String abc = "http://www.petschannel.com/";
String imageSrc = line.substring(startIndex,endIndex);
//complete full url
String xyz = abc +imageSrc;
xyz = xyz.substring(0,xyz.indexOf('"'));
xyz = xyz +";";
imageC += xyz;
mStrings = imageC.split(";");
line = reader.readLine();
}
if(line.contains("../../") == false)
{
line = reader.readLine();
}
if (line.contains("Gnametag"))
{
int startIndex = line.indexOf("Gnametag") + 10;
int endIndex = line.indexOf("<", startIndex + 1);
String gname = line.substring(startIndex,endIndex);
textC += "Name: "+gname+ "\n";
}
if (line.contains("Last Update"))
{
reader.close();
}
}
// Close the reader
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
答案 0 :(得分:0)
这样的事情:
final ProgressDialog myDialog = ProgressDialog.show(this, "Title", "Message");
Thread thread = new Thread(new Runnable() {
public void run() {
/* Your code goes here */
mHandler.sendEmptyMessage(0);
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
myDialog.dismiss();
}
}
}
thread.start();
答案 1 :(得分:0)
首先,您正在主线程上进行网络呼叫,出于性能原因,这是一个经典的禁忌,等等。永远不要在主(ui)线程上执行任何可能耗时的操作。
我建议使用AsyncTask,在这种情况下,确保您的网络调用将在工作线程中完成,并将结果发回主线程。
AsyncTask具有管理进度条的方法,onProgressUpdate
和publishProgress
可帮助您解决所述问题。有很多关于此的好文章,here is one。