【问题标题】:How can I workaround the ImageView?如何解决 ImageView?
【发布时间】:2014-12-12 20:50:29
【问题描述】:

大家好,我正在开发一个带有地图的应用程序,并且我使用四个 TextView 和一个 ImageView 进行了自定义信息窗口。现在我知道 InfoWindow 是一个预渲染的图像,所以我的问题是我想为每个标记显示一个个性化的图像:一切正常,但在第一次点击时,第二次点击时只有一个空白区域,图像成功显示。

第一次点击:

然后当我第二次点击标记时:

我显然想避免点击两次来制作图片..这是一个大问题。我使用 Picasso 库从 Web 加载图像,并保留来自四个 xml 文件的图像 URL。所以我理解问题是,当系统缓存图像时,系统可以加载图像。所以我想到了这个解决方法:我在应用程序开始调用 Asynctask 时将图像加载到不可见的 Imageview 上,但这仅适用于它从 xml 中保留的最后一个 URL,而不适用于其他标记。 所以我想问你是否有一些想法来做这件事。

在我的代码下面:

一开始我调用了AsyncTask:

View v = this.getWindow().getDecorView().findViewById(R.id.immaginenascosta);
CacheTask cacheTask = new CacheTask(v);
cacheTask.execute();

CacheTask,扩展 AsyncTask 的类从 Internet 下载 xml 文件并将它们保存在 SD 卡上(在后台),然后它从 xml 读取(在 SD 卡上)并在 Gone ImageView 上加载图像:

缓存任务

public class CacheTask extends AsyncTask<Void, Void, Void>{

    String [] imgurlarray = {};
    int dim = 0;

    String root = "http://www.emmebistudio.com/markers_Predappio_living/";
    String [] arraymarkers = {"markers_history.xml","markers_hotel.xml","markers_restaurant.xml","markers_souvenir.xml"};

    String pathdirectory = "/sdcard/PredappioLiving";

    private View view;


    public CacheTask(View view){
        this.view = view;

    }

    public void MakeCache (View v)
    {

    }


    @Override
    protected Void doInBackground(Void... params) {


        for (int i = 0; i < arraymarkers.length; i++)
        {
            String urlcompleta = root+arraymarkers[i];

            //Estraggo la stringa del nome dall'url--------------------------------------------------------------

            String stringurl = urlcompleta.toString();          // Prende: http://www.emmebistudio.com/Predappio_living/markers.xml e lo mette in array
            String [] urlarray = stringurl.split("/");  //           ^   ^          ^                 ^             ^
                                                        //           |   |          |                 |             |
                                                        //           |   |          |                 |             |
            String nomefile = urlarray[4];              //           0   1          2                 3             4  

            //Adattare a seconda della posizione definitiva dei file XML

            //----------------------------------------------------------------------------------------------------


            try {
                URL url = new URL(urlcompleta);

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);
                urlConnection.connect();

                File dir = new File(pathdirectory);
                dir.mkdirs();

                File fileWithinMyDir = new File(dir, nomefile);
                FileOutputStream fileOutput = new FileOutputStream(fileWithinMyDir);

                InputStream inputStream = urlConnection.getInputStream();

                int totalSize = urlConnection.getContentLength();   //mi salvo la lunghezza del file da salvare
                int downloadedSize = 0;
                byte[] buffer = new byte[1024];
                int bufferLength = 0;   //per salvare usiamo una dimensione temporanea del buffer
                                        // salvo attraverso il buffer di input e scrivo il contenuto nel file.
                while((bufferLength = inputStream.read(buffer)) > 0){
                    fileOutput.write(buffer,0,bufferLength);
                    downloadedSize += bufferLength;
                    int progress = (int)(downloadedSize*100/totalSize);
                }

                fileOutput.close();
            }

            catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        for (int i = 0; i < arraymarkers.length; i++)
        {
            String urlcompleta = root+arraymarkers[i];

            //Estraggo la stringa del nome dall'url--------------------------------------------------------------

            String stringurl = urlcompleta.toString();          // Prende: http://www.emmebistudio.com/Predappio_living/markers.xml e lo mette in array
            String [] urlarray = stringurl.split("/");  //           ^   ^          ^                 ^             ^
                                                        //           |   |          |                 |             |
                                                        //           |   |          |                 |             |
            String nomefile = urlarray[4];              //           0   1          2                 3             4  

            //Adattare a seconda della posizione definitiva dei file XML

            //----------------------------------------------------------------------------------------------------

            try{
                /* * * * *   Inizio Parsing    * * * * */
                /***************************************/
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(new FileInputStream(pathdirectory+"/"+nomefile));
                doc.getDocumentElement().normalize();

                NodeList markers = doc.getElementsByTagName("marker");

                ImageView []image = new ImageView[100];
                image[i]=(ImageView) view.findViewById(R.id.immaginenascosta);
                //ImageView image = (ImageView) view.findViewById(R.id.immaginenascosta);
                for (int j=0; j<markers.getLength(); j++){
                    Element item = (Element) markers.item(i);
                    String urlimmagine = item.getAttribute("immagine");

                    Picasso.with(view.getContext())
                        .load(urlimmagine)
                        .error(R.drawable.ic_launcher)  //in caso di errore fa vedere questa immagine (un triangolo penserei)
                        .resize(150, 110)
                        .into(image[i]);                    

                }
            /***************************************/
                /* * * * *    Fine Parsing     * * * * */
            }catch(Exception e){
                e.printStackTrace();
            }


        super.onPostExecute(result);
    }
}
}

这是“Gone”ImageView的布局:

<ImageView 
    android:id="@+id/immaginenascosta"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:visibility="gone"/>

这就是 setInfoWindowAdapter:

map.setInfoWindowAdapter(new InfoWindowAdapter() {

    View v = getLayoutInflater().inflate(R.layout.custom_info_window, null);



    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {

    //Prova immagine custom
    /***********************************/
    //final ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Attendere...", "Caricamento delle immagini in corso..", true);

    BuildInfoMatrix req = new BuildInfoMatrix();

    String nome = marker.getTitle();
    String currentUrl = "";
    //String currentUrl=req.findImageUrl(nome);
    int vuoto = -15;
    try{
        currentUrl=req.findImageUrl(nome);
    }catch(Exception e){
        currentUrl = "http://upload.wikimedia.org/wikipedia/commons/b/bb/XScreenSaver_simulating_Windows_9x_BSOD.png";
    }
    if (currentUrl == null)
    {
        currentUrl = "http://upload.wikimedia.org/wikipedia/commons/b/bb/XScreenSaver_simulating_Windows_9x_BSOD.png";
    } 
    ImageView image;
    image = (ImageView) v.findViewById(R.id.image_nuvoletta);

    Picasso.with(v.getContext())
        .load(currentUrl)
        .error(R.drawable.ic_launcher)  //in caso di errore fa vedere questa immagine (un triangolo penserei)
        .resize(150, 110)
        .into(image, new Callback(){

        @Override
        public void onSuccess(){

        }

        @Override
        public void onError(){

        }
}); 


    /***********************************/


    /* Distanza a piedi e macchina sulla nuvoletta */
    /***********************************************/
    GPSTracker gpsTracker = new GPSTracker(MainActivity.this);

    if (gpsTracker.canGetLocation())
    {
        String stringLatitude = String.valueOf(gpsTracker.latitude);
        String stringLongitude = String.valueOf(gpsTracker.longitude);
        double currentLat = Double.parseDouble(stringLatitude);
        double currentLng = Double.parseDouble(stringLongitude);

        double destLat = marker.getPosition().latitude;
        double destLng = marker.getPosition().longitude;

        final float[] results = new float[3];
        Location.distanceBetween(currentLat, currentLng, destLat, destLng, results);

        float metri = results[0];
        float km = Math.round((double)metri/1000);

        int minuti_persona = (int)Math.round(metri/125);    //125 metri al minuto -> velocità media di 2,5 m/s
        int minuti_auto = (int)Math.round(km/0.7);          //700 metri al minuto -> velocità media di 42 km/h 


        /***********************************************/



        TextView tvTitle = (TextView) v.findViewById(R.id.title);
        TextView tvSnippet = (TextView) v.findViewById(R.id.snippet);
        tvSnippet.setTypeface(tvSnippet.getTypeface(), Typeface.ITALIC); //indirizzo in corsivo
        TextView tvPedonal_distance = (TextView) v.findViewById(R.id.pedonal_time);
        TextView tvCar_distance = (TextView) v.findViewById(R.id.car_time);
        tvTitle.setText(marker.getTitle());
        tvSnippet.setText(marker.getSnippet());

        if(minuti_persona <=0)          // Stampa tempo per coprire la distanza
        {
            tvCar_distance.setText("A piedi: meno di un minuto");
        }else
        {
            tvPedonal_distance.setText("A piedi: "+minuti_persona+ " minuti");
        }

        if(minuti_auto <= 0)
        {
            tvCar_distance.setText("In auto: meno di un minuto");                                   
        }else
        {
            tvCar_distance.setText("In auto: " +minuti_auto+ " minuti");
        }

        return v;
   }else
   {
        TextView tvTitle = (TextView) v.findViewById(R.id.title);
        TextView tvSnippet = (TextView) v.findViewById(R.id.snippet);
        tvTitle.setText(marker.getTitle());
        tvSnippet.setText(marker.getSnippet());
        return v;
   }

}

});

谢谢大家。

【问题讨论】:

  • 为什么它的可见性消失了?第二次点击气球会发生什么?
  • 我做了一个不可见的 imageview 来在 InfoWindow 的 ImageViews 上预加载图像。当我点击气球出现一个对话框

标签: android imageview google-maps-android-api-2 picasso


【解决方案1】:

由于图像加载的异步特性,诀窍是在图像加载到内存后“使显示的信息窗口无效”。为此,您必须跟踪上次点击的标记,并检查它是否仍在显示其信息窗口。然后再次调用showInfoWindow() 以强制更新信息窗口:

if (markerShowingInfoWindow != null && markerShowingInfoWindow.isShowingInfoWindow()) {
    markerShowingInfoWindow.showInfoWindow();
}

更多详情请参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2018-06-01
    • 1970-01-01
    相关资源
    最近更新 更多