(Android App)尝试将AlertDialog .setIcon()设置为从URL

时间:2016-10-09 09:18:04

标签: java android android-studio

目前正在制作具有位置屏幕的应用程序,当按下地图标记时,会弹出AlertDialog并显示一些信息。我想将AlertDialog的图标设置为与来自URL的该位置相关联的图像。图像存储的位置太多,无法在本地存储。

 public Drawable pGraphic = null;

public class LoadImageFromWeb extends AsyncTask<String, Void, Drawable> {
    protected Drawable doInBackground(String... urls) {


        try {
            InputStream is = (InputStream) new URL(urls[0]).getContent();

            Drawable d = Drawable.createFromStream(is, "src name");
            BT_debugger.showIt(d.toString());
            return d;
        } catch (Exception e) {
            BT_debugger.showIt(e.toString());
            return null;
        }

    }
    protected void onPostExecute(Drawable result) {
        BT_debugger.showIt("Image Loaded");
        pGraphic = result;


    }
}
//handleMarkerClick..
public void handleMarkerClick(final int markerIndex) {

    BT_debugger.showIt(fragmentName + ":handleMarkerClick");

    //vars used in callout bubble...
    BT_item tappedItem = null;
    String latitude = "";
    String longitude = "";
    String title = "";
    String subTitle = "";
    String loadScreenWithItemId = "";
    String loadScreenWithNickname = "";
    String calloutTapChoice = "";
    Drawable pinGraphic = null;

    //if marker index == -1 then the user tapped the device's location icon...
    if(markerIndex == -1){
        BT_debugger.showIt(fragmentName + ":handleMarkerClick. Device location tapped");

        //use the graphic for the device location...
        pinGraphic = getResources().getDrawable(R.drawable.bt_screen_map_marker_device);

        //latitude / longitude is current location or last saved location...
        if(mapView.isMyLocationEnabled()){

            Location deviceLoc = mapView.getMyLocation();
            latitude = String.valueOf(deviceLoc.getLatitude());
            longitude = String.valueOf(deviceLoc.getLongitude());

            //title, subTitle...
            title = pokegoaus_appDelegate.rootApp.getRootDevice().getDeviceModel();
            subTitle = getString(R.string.mapUserLocationDescription) + "\nLatitude: " + latitude + "\nLongitude: " + longitude; 

        }else{

            //latitude / longitude is last current saved...
            latitude = goaus_appDelegate.rootApp.getRootDevice().getDeviceLatitude();
            longitude = goaus_appDelegate.rootApp.getRootDevice().getDeviceLongitude();

            //title, subTitle...
            title = goaus_appDelegate.rootApp.getRootDevice().getDeviceModel();
            subTitle = getString(R.string.mapUserLocationDescription) + "\nLatitude: " + latitude + "\nLongitude: " + longitude; 

        }//isMyLocationEnabled...

    }else{

        //get the BT_item at this index...
        tappedItem = childItems.get(markerIndex);
        latitude = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "latitude", "");
        longitude = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "longitude", "");
        title = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "title", "");
        subTitle = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "subTitle", "");
        loadScreenWithItemId = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "loadScreenWithItemId", "");
        loadScreenWithNickname = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "loadScreenWithNickname", "");
        calloutTapChoice = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "calloutTapChoice", "");


        String pinColor = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "pinColor", "red");
        String locationImage = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "locationImage", "");
        new LoadImageFromWeb().execute("http://pheds.com.au/example1.png");


        BT_debugger.showIt(fragmentName + ":handleMarkerClick. Tapped: \"" + title + "\"");

    }//not the device's location...

    //are we showing the details button on this locations pup-up bubble?
    boolean showDetailsButton = false;
    if(loadScreenWithItemId.length() > 1 || loadScreenWithNickname.length() > 1){
        showDetailsButton = true;
    }

    //if we are showing directions we are not showing details bubble...
    if(loadScreenWithItemId.equalsIgnoreCase("showDirections")){
        showDetailsButton = false;
    }

    //if we did not find load screen from id or nickname, look for a load sceen object...
    if(!showDetailsButton){
        try{
            if(tappedItem != null){
                JSONObject obj = tappedItem.getJsonObject();
                if(obj.has("loadScreenObject")){
                    showDetailsButton = true;
                }
            }
        }catch(Exception e){
            showDetailsButton = false;
        }
    }
    pinGraphic = pGraphic;
    final AlertDialog myAlert = new AlertDialog.Builder(this.getActivity()).create();
    myAlert.setTitle(title);
    myAlert.setMessage(subTitle);
    myAlert.setIcon(pinGraphic);
    myAlert.setCancelable(false);
    myAlert.setButton2(getString(R.string.ok), new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            myAlert.dismiss();
        } }); 

    //do we show details button?
    if(showDetailsButton){
        myAlert.setButton(getString(R.string.details), new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                myAlert.dismiss();
                showDetailsScreen(markerIndex);
         } }); 
    }

    //do we show the driving directions button?
    if(loadScreenWithItemId.equalsIgnoreCase("showDirections") || calloutTapChoice.equalsIgnoreCase("showDirections")){
        myAlert.setButton(getString(R.string.mapDrivingDirections), new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                myAlert.dismiss();
                showDirections(markerIndex);
        } }); 
    }

    //show...
    myAlert.show();

}

似乎正在下载图像。但我不确定如何处理下载的图像并在我的AlertDialog中使用它。使用LoadImageFromWeb作为AsyncTask类我不知道如何将结果用作Drawable。

提前致谢

Kristan Halls

完美无瑕的应用

2 个答案:

答案 0 :(得分:2)

好像你不是在等待Drawable下载。您立即将其设置为AlertDialog的图标。

最好使用Glide从网上下载和显示图片。它比标准的AsyncTask更有效,更易于使用。 以下是您如何使用Glide -

Glide.with(this)
    .load("http://pheds.com.au/example1.png")
    .into(new SimpleTarget<GlideDrawable>(drawableWidth, drawableHeight) {
        @Override
        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
            myAlert.setIcon(resource);
        }
    });

编辑: 导入以下内容 -

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

答案 1 :(得分:1)

首先使用setFeatureDrawable(int featureId,Drawable drawable),如下所示:

Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setFeatureDrawable(Window.FEATURE_LEFT_ICON, drawableFromUrl(YOUR_URL)); 
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Dialog Title");
dialog.show();

要获取图像(https://stackoverflow.com/a/9490060/4198633):

public static Drawable drawableFromUrl(String url) throws IOException {
    Bitmap x;

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.connect();
    InputStream input = connection.getInputStream();

    x = BitmapFactory.decodeStream(input);
    return new BitmapDrawable(x);
}

当然,你需要这个:

<uses-permission android:name="android.permission.INTERNET" />