我该如何解决ImageView?

时间:2014-10-17 09:38:08

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

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

首先点按:first_tap

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

我显然想避免轻拍两次来制作图片..这是个大问题。我使用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上加载图像:

CacheTask

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);
    }
}
}

这就是&#34; Gone&#34;的布局。 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;
   }

}

});

谢谢大家。

1 个答案:

答案 0 :(得分:0)

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

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

有关详细信息,请参阅: