首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解决ImageView问题?

问如何解决ImageView问题?
EN

Stack Overflow用户
提问于 2014-10-17 17:38:08
回答 1查看 173关注 0票数 1

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

第一次点击:

​

然后当我第二次点击记号笔的时候:

​

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

下面是我的代码:

在开始时,我调用AsyncTask:

代码语言:javascript
复制
View v = this.getWindow().getDecorView().findViewById(R.id.immaginenascosta);
CacheTask cacheTask = new CacheTask(v);
cacheTask.execute();

扩展AsyncTask的类CacheTask从互联网上下载xml文件并保存到SDcard (后台),然后读取xml (在SDcard上)并在Gone ImageView上加载图像:

CacheTask

代码语言:javascript
复制
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的布局:

代码语言:javascript
复制
<ImageView 
    android:id="@+id/immaginenascosta"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:visibility="gone"/>

这是setInfoWindowAdapter:

代码语言:javascript
复制
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;
   }

}

});

谢谢大家。

EN

回答 1

Stack Overflow用户

发布于 2014-10-17 17:53:57

由于图像加载的异步性质,诀窍在于一旦图像加载到内存中,就使显示的信息窗口“无效”。要做到这一点,您必须跟踪最后点击的标记,并检查它是否仍在显示其信息窗口。然后再次调用showInfoWindow(),强制对信息窗口进行可视化更新:

代码语言:javascript
复制
if (markerShowingInfoWindow != null && markerShowingInfoWindow.isShowingInfoWindow()) {
    markerShowingInfoWindow.showInfoWindow();
}

有关更多详细信息,请参阅:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26422161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档