我要做的是在用户点击一个名为location_Button的按钮后获取用户的位置,然后显示一个显示有关其位置信息的框。我试过这样的:
Button location_Button=(Button) findViewById(R.id.location_button);
location_Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Define a listener that responds to location updates
progressDialog = ProgressDialog.show(Settings.this, "", "Loading...");
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat =location.getLatitude();
lon = location.getLongitude();
try{
addresses=(geocoder.getFromLocation(lat, lon, 1));
if (addresses.size() > 0) {
String city = addresses.get(0).getAddressLine(1);
String id = city.substring(0,city.length()-5);
String state1=String.valueOf(id.charAt(id.length()-3));
String state2=String.valueOf(id.charAt(id.length()-2));
String STATE = state1+state2;
locationManager.removeUpdates(this);
progressDialog.dismiss();
//alert dialog is established and displayed here
}
else {
//tv.setText("Oops...");
}
}catch(IOException e){
e.printStackTrace();
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
问题是进度对话框永远不会被解雇。按下按钮时没有进度对话框,它会搜索然后显示该框,进度对话框继续说明加载并且永远不会被解除。我的目标是在建立位置后取消进度对话框,同时应弹出警告对话框,但事实并非如此。进度对话框的位置不正确?
答案 0 :(得分:1)
仅仅因为Android始终是异步的,您必须使用线程来使用进度对话框。一个例子:
在您的代码中,当您想要启动对话框时,请调用异步类:
Button location_Button=(Button) findViewById(R.id.location_button);
location_Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LocationChanged locationChanged = new LocationChanged(MainActivity.this, "Loading...");
locationChanged.execute();
}
现在您需要创建LocationChanged.java:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class LocationChanged extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
private String message;
public LocationChanged (Context context, String message) {
this.context = context;
this.message = message;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show (context, null, message);
}
@Override
protected Void doInBackground( Void... params ) {
// Here you add your code.
return null;
}
@Override
protected void onPostExecute( Void result ) {
super.onPostExecute (result);
progressDialog.dismiss();
// You can add code to be executed after the progress (may be a result).
}
}