如何重复使用已导入到此 RSS 片段的详细视图中的图像

How do I reuse the image that is already imported to the detail view of this RSS Fragment

我有这段代码可以接收 RSS 提要并将其显示到一行中,但是,一旦单击该行,它就不会保留图像。如何实现从列表视图到详细视图的图像传输。

这是 RSS Reader 查看

package com.sieae.jamaicaobserver.rss.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 *  This activity is used to display a list of rss items
 */

public class RssFragment extends Fragment {

    private RSSFeed myRssFeed = null;
    private Activity mAct;
    private LinearLayout ll;
    private RelativeLayout pDialog; 

    public class MyCustomAdapter extends ArrayAdapter<RSSItem> {

         public MyCustomAdapter(Context context, int textViewResourceId,
                 List<RSSItem> list) {
                super(context, textViewResourceId, list);
         }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) { 
            View row = convertView;

            final ViewHolder holder;

            if(row==null){

                LayoutInflater inflater=mAct.getLayoutInflater();
                row=inflater.inflate(R.layout.fragment_rss_row, null);

                holder = new ViewHolder();

                holder.listTitle=(TextView)row.findViewById(R.id.listtitle);
                holder.listPubdate=(TextView)row.findViewById(R.id.listpubdate);
                holder.listDescription=(TextView)row.findViewById(R.id.shortdescription);
                holder.listThumb =(ImageView)row.findViewById(R.id.listthumb);

                row.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.listTitle.setText(myRssFeed.getList().get(position).getTitle());   
            holder.listPubdate.setText(myRssFeed.getList().get(position).getPubdate());

            String html = myRssFeed.getList().get(position).getRowDescription();

            holder.listDescription.setText(html);

            holder.listThumb.setImageDrawable(null);

            //get Imageloader
            ImageLoader imageLoader = Helper.initializeImageLoader(mAct);

            //LayoutInflater inflater = (LayoutInflater) mAct
            //      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //View v = inflater.inflate(R.layout.fragment_rss, null);

            //ListView listView = (ListView) v.findViewById(R.id.rsslist);

            //pausing on scrolling the listview
            //boolean pauseOnScroll = true; // or true
            //boolean pauseOnFling = true; // or false
            //PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
            //listView.setOnScrollListener(listener);

            String thumburl = myRssFeed.getList().get(position).getThumburl();
            if (thumburl != "" && thumburl != null){
                //setting the image
                imageLoader.displayImage(myRssFeed.getList().get(position).getThumburl(), holder.listThumb, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        if (10 > loadedImage.getWidth() || 10 > loadedImage.getHeight()) {
                            // handle scaling
                            holder.listThumb.setVisibility(View.GONE);
                        } else {
                            holder.listThumb.setVisibility(View.VISIBLE);
                        }

                    }
                });
            } else {
                holder.listThumb.setVisibility(View.GONE);
            }

            return row;
         }

    }

    static class ViewHolder {
          TextView listTitle;
          TextView listPubdate;
          TextView listDescription;
          ImageView listThumb;
          int position;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ll = (LinearLayout) inflater.inflate(R.layout.fragment_rss, container, false);
        setHasOptionsMenu(true);

        if ((getResources().getString(R.string.ad_visibility).equals("0"))){
            // Look up the AdView as a resource and load a request.
            AdView adView = (AdView) ll.findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.loadAd(adRequest);
        }
        return ll;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAct = getActivity();
        Log.v("INFO", "onAttach() called");
        new MyTask().execute();
    }


    private class MyTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected void onPreExecute(){
            pDialog = (RelativeLayout) ll.findViewById(R.id.progressBarHolder);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                String weburl = RssFragment.this.getArguments().getString(MainActivity.DATA);
                URL rssUrl = new URL(weburl);
                SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
                SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
                XMLReader myXMLReader = mySAXParser.getXMLReader();
                RSSHandler myRSSHandler = new RSSHandler();
                myXMLReader.setContentHandler(myRSSHandler);
                InputSource myInputSource = new InputSource(rssUrl.openStream());
                myXMLReader.parse(myInputSource);

                myRssFeed = myRSSHandler.getFeed();

            } catch (MalformedURLException e) {
                e.printStackTrace();                
            } catch (ParserConfigurationException e) {
                e.printStackTrace();    
            } catch (SAXException e) {
                e.printStackTrace();            
            } catch (IOException e) {
                e.printStackTrace();    
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            ListView listview = (ListView) ll.findViewById(R.id.rsslist);

            if (myRssFeed != null) {
                MyCustomAdapter adapter = new MyCustomAdapter(mAct,
                        R.layout.fragment_rss_row, myRssFeed.getList());
                listview.setAdapter(adapter);

                listview.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View v,
                            int position, long id) {
                        Intent intent = new Intent(mAct,
                                RssDetailActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("keyTitle", myRssFeed
                                .getItem(position).getTitle());
                        bundle.putString("keyDescription",
                                myRssFeed.getItem(position).getDescription());
                        bundle.putString("keyLink", myRssFeed.getItem(position)
                                .getLink());
                        bundle.putString("keyPubdate",
                                myRssFeed.getItem(position).getPubdate());
                        bundle.putString("keyThumburl",
                                myRssFeed.getItem(position).getThumburl());
                        intent.putExtras(bundle);
                        startActivity(intent);

                    }
                });

            } else {
                Helper.noConnection(mAct, true);
            }

            if (pDialog.getVisibility() == View.VISIBLE) {
                pDialog.setVisibility(View.GONE);
                //feedListView.setVisibility(View.VISIBLE);
                Helper.revealView(listview,ll);
            }
            super.onPostExecute(result);
        }

    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.rss_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.refresh_rss:
            new MyTask().execute();
            return true;
        case R.id.info:    
            //show information about the feed in general in a dialog 
            if (myRssFeed!=null)
            {
                String FeedTitle = (myRssFeed.getTitle());
                String FeedDescription = (myRssFeed.getDescription());
                //String FeedPubdate = (myRssFeed.getPubdate()); most times not present
                String FeedLink = (myRssFeed.getLink());

                AlertDialog.Builder builder = new AlertDialog.Builder(mAct);

                String titlevalue = getResources().getString(R.string.feed_title_value);
                String descriptionvalue = getResources().getString(R.string.feed_description_value);
                String linkvalue = getResources().getString(R.string.feed_link_value);

                if (FeedLink.equals("")){
                     builder.setMessage(titlevalue+": \n"+FeedTitle+
                           "\n\n"+descriptionvalue+": \n"+FeedDescription);
                } else {
                     builder.setMessage(titlevalue+": \n"+FeedTitle+
                           "\n\n"+descriptionvalue+": \n"+FeedDescription +
                           "\n\n"+linkvalue+": \n"+FeedLink);
                };

                     builder.setNegativeButton(getResources().getString(R.string.ok),null)
                     .setCancelable(true);
                builder.create();
                builder.show();

            }else{

            }     
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

这是详细视图

    package com.sieae.jamaicaobserver.rss.ui;

import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.sieae.jamaicaobserver.R;
import com.sieae.jamaicaobserver.fav.FavDbAdapter;
import com.sieae.jamaicaobserver.util.WebHelper;
import com.sieae.jamaicaobserver.web.WebviewActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 *  This activity is used to display details of a rss item
 */

public class RssDetailActivity extends ActionBarActivity {

    private WebView wb;
    private FavDbAdapter mDbHelper;
    private Toolbar mToolbar;

    String date;
    String link;
    String title;
    String description;
    String favorite;
    String listThumb;

    @SuppressLint("SetJavaScriptEnabled")@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rss_details);
        mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        TextView detailsTitle = (TextView) findViewById(R.id.detailstitle);
        TextView detailsPubdate = (TextView) findViewById(R.id.detailspubdate);

        Bundle bundle = this.getIntent().getExtras();

        detailsTitle.setText(bundle.getString("keyTitle"));
        detailsPubdate.setText(bundle.getString("keyPubdate"));
        date = (bundle.getString("keyPubdate"));
        link = (bundle.getString("keyLink"));
        title = (bundle.getString("keyTitle"));
        description = (bundle.getString("keyDescription"));
        favorite = (bundle.getString("keyFavorites"));
        listThumb = (bundle.getString("keyThumburl"));

        wb = (WebView) findViewById(R.id.descriptionwebview);

        //parse the html and apply some styles
        Document doc = Jsoup.parse(description);
        String html = WebHelper.docToBetterHTML(doc, this);;

        wb.getSettings().setJavaScriptEnabled(true);
        wb.loadDataWithBaseURL(link, html , "text/html", "UTF-8", "");
        Log.v("INFO", "Wordpress HTML: " + html);
        wb.setBackgroundColor(Color.argb(1, 0, 0, 0));
        wb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wb.getSettings().setDefaultFontSize(WebHelper.getWebViewFontSize(this));
        wb.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != null && (url.startsWith("http://") || url.startsWith("http://"))) {
                    Intent mIntent = new Intent(RssDetailActivity.this, WebviewActivity.class);
                    mIntent.putExtra(WebviewActivity.URL, url);
                    startActivity(mIntent);
                    return true;
                } else {
                    Uri uri = Uri.parse(url);
                    Intent ViewIntent = new Intent(Intent.ACTION_VIEW, uri);

                    // Verify it resolves
                    PackageManager packageManager = getPackageManager();
                    List<ResolveInfo> activities = packageManager.queryIntentActivities(ViewIntent, 0);
                    boolean isIntentSafe = activities.size() > 0;

                    // Start an activity if it's safe
                    if (isIntentSafe) {
                        startActivity(ViewIntent);
                    }
                    return true;
                }
            }
        });

        if ((getResources().getString(R.string.ad_visibility).equals("0"))) {
            // Look up the AdView as a resource and load a request.
            AdView adView = (AdView) findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.loadAd(adRequest);
        }

        Button btnOpen = (Button) findViewById(R.id.openbutton);

        //Listening to button event
        btnOpen.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                Uri.parse(link));
                startActivity(intent);

            }
        });

        Button btnFav = (Button) findViewById(R.id.favoritebutton);

        //Listening to button event
        btnFav.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                mDbHelper = new FavDbAdapter(RssDetailActivity.this);
                mDbHelper.open();

                if (mDbHelper.checkEvent(title, description, date, link, "", "", "rss")) {
                    // Item is new
                    mDbHelper.addFavorite(title, description, date, link, "", "", "rss");
                    Toast toast = Toast.makeText(RssDetailActivity.this, getResources().getString(R.string.favorite_success), Toast.LENGTH_LONG);
                    toast.show();
                } else {
                    Toast toast = Toast.makeText(RssDetailActivity.this, getResources().getString(R.string.favorite_duplicate), Toast.LENGTH_LONG);
                    toast.show();
                }
            }
        });


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.share:
                String html = description;
                html = html.replaceAll("<(.*?)\>", ""); //Removes all items in brackets
                html = html.replaceAll("<(.*?)\\n", ""); //Must be undeneath
                html = html.replaceFirst("(.*?)\>", ""); //Removes any connected item to the last bracket
                html = html.replaceAll("&nbsp;", "");
                html = html.replaceAll("&amp;", "");
                html = html.replaceAll("&lsquo;", "‘");

                String linkvalue = getResources().getString(R.string.item_share_begin);
                String seenvalue = getResources().getString(R.string.item_share_middle);
                String appvalue = getResources().getString(R.string.item_share_end);
                String applicationName = getResources().getString(R.string.app_name);
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                //this is the text that will be shared
                sendIntent.putExtra(Intent.EXTRA_TEXT, (html + linkvalue + link + seenvalue + applicationName + appvalue));
                sendIntent.putExtra(Intent.EXTRA_SUBJECT, title); //you can replace title with a string of your choice
                sendIntent.setType("text/plain");
                startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share_header)));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.rss_detail_menu, menu);
        return true;
    }

}

您可以通过 Intent 作为 ByteArray 发送图像或尝试从 URL 加载。从 URL 加载是首选,因为它不会在通过 Intent 传递大型位图图像时带来 OutOfMemoryException 或任何其他问题。如果图片比较小,可以通过Intent传递。

下面的代码显示了这两种方法。实施适合您的需要或适用于您的 URL 案例。

发件人Activity

//Download image from thumbUrl to bitmap
URL newurl = new URL(myRssFeed.getItem(position).getThumburl()); 
Bitmap bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());

Intent intent = new Intent(mAct, RssDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyDescription", myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
bundle.putString("keyPubdate",myRssFeed.getItem(position).getPubdate());

//pass image url
bundle.putString("keyThumburl", myRssFeed.getItem(position).getThumburl());

//sent image bitmap byte array
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
bundle.putByteArray("byteArray", bs.toByteArray());

intent.putExtras(bundle);
startActivity(intent);

接收者Activity

   Bundle bundle = this.getIntent().getExtras();

   //load from bitmap bytearray
   Bitmap bitmap = BitmapFactory.decodeByteArray(bundle.getByteArray("byteArray"),0,bundle.getByteArray("byteArray").length);        
   imageView.setImageBitmap(bitmap);

   //or load from image url

    new LoadImage().execute(bundle.getString("keyThumbUrl")); 

创建一个 AsyncTask 以从 URL 通过 Intent

发送的图像加载到 ImageView
private class LoadImage extends AsyncTask<String, String, Bitmap> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }
         protected Bitmap doInBackground(String... args) {
             try {
                  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());     
            } catch (Exception e) {
                  e.printStackTrace();
            }
            return bitmap;
         }

         protected void onPostExecute(Bitmap image) {

             if(image != null){
              imageView.setImageBitmap(image);                
             } else{
              Toast.makeText(RssDetailActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();     
             }
         }
     }

}