Fragment类中的位图值

时间:2015-10-07 14:04:46

标签: android android-fragments bitmap

我试图在Fragment类中获取我的mImageView的位图。 我注意到我可以看到正确的drawable,但有时只创建位图,而大多数情况下都是Null。 这是代码:

package com.example.android.displayingbitmaps.ui;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.android.displayingbitmaps.R;
import com.example.android.displayingbitmaps.util.ImageFetcher;
import com.example.android.displayingbitmaps.util.ImageWorker;
import com.example.android.displayingbitmaps.util.Utils;

/**
 * This fragment will populate the children of the ViewPager from {@link ImageDetailActivity}.
 */
public class ImageDetailFragment extends Fragment {
    private static final String IMAGE_DATA_EXTRA = "extra_image_data";
    private String mImageUrl;
    private ImageView mImageView;
    private ImageFetcher mImageFetcher;

    /**
     * Factory method to generate a new instance of the fragment given an image number.
     *
     * @param imageUrl The image url to load
     * @return A new instance of ImageDetailFragment with imageNum extras
     */
    public static ImageDetailFragment newInstance(String imageUrl) {
        final ImageDetailFragment f = new ImageDetailFragment();

        final Bundle args = new Bundle();
        args.putString(IMAGE_DATA_EXTRA, imageUrl);
        f.setArguments(args);

        return f;
    }

    /**
     * Empty constructor as per the Fragment documentation
     */
    public ImageDetailFragment() {}

    /**
     * Populate image using a url from extras, use the convenience factory method
     * {@link ImageDetailFragment#newInstance(String)} to create this fragment.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageUrl = getArguments() != null ? getArguments().getString(IMAGE_DATA_EXTRA) : null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate and locate the main ImageView
        final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
        mImageView = (ImageView) v.findViewById(R.id.imageView);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Use the parent activity to load the image asynchronously into the ImageView (so a single
        // cache can be used over all pages in the ViewPager
        if (ImageDetailActivity.class.isInstance(getActivity())) {
            mImageFetcher = ((ImageDetailActivity) getActivity()).getImageFetcher();
            mImageFetcher.loadImage(mImageUrl, mImageView);
            BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
            Bitmap bitmap = drawable.getBitmap();
            Toast.makeText(getActivity(), "Drawable is: "+drawable,Toast.LENGTH_SHORT).show();        }

        // Pass clicks on the ImageView to the parent activity to handle
        if (OnClickListener.class.isInstance(getActivity()) && Utils.hasHoneycomb()) {
            mImageView.setOnClickListener((OnClickListener) getActivity());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mImageView != null) {
            // Cancel any pending image work
            ImageWorker.cancelWork(mImageView);
            mImageView.setImageDrawable(null);
        }
    }
}

FragmentActivity类

import android.annotation.TargetApi;
    import android.app.ActionBar;
    import android.os.Build.VERSION_CODES;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentStatePagerAdapter;
    import android.support.v4.app.NavUtils;
    import android.support.v4.view.ViewPager;
    import android.util.DisplayMetrics;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.WindowManager.LayoutParams;
    import android.widget.ImageView;
    import android.widget.Toast;

    import com.example.android.displayingbitmaps.BuildConfig;
    import com.example.android.displayingbitmaps.R;
    import com.example.android.displayingbitmaps.provider.Images;
    import com.example.android.displayingbitmaps.util.ImageCache;
    import com.example.android.displayingbitmaps.util.ImageFetcher;
    import com.example.android.displayingbitmaps.util.Utils;

    public class ImageDetailActivity extends FragmentActivity implements OnClickListener {
        private static final String IMAGE_CACHE_DIR = "images";
        public static final String EXTRA_IMAGE = "extra_image";

        private ImagePagerAdapter mAdapter;
        private ImageFetcher mImageFetcher;
        private ViewPager mPager;
        private ImageView mImageView;

        @TargetApi(VERSION_CODES.HONEYCOMB)
        @Override
        public void onCreate(Bundle savedInstanceState) {
            if (BuildConfig.DEBUG) {
                Utils.enableStrictMode();
            }
            super.onCreate(savedInstanceState);
            setContentView(R.layout.image_detail_pager);

            // Fetch screen height and width, to use as our max size when loading images as this
            // activity runs full screen
            final DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            final int height = displayMetrics.heightPixels;
            final int width = displayMetrics.widthPixels;

            // For this sample we'll use half of the longest width to resize our images. As the
            // image scaling ensures the image is larger than this, we should be left with a
            // resolution that is appropriate for both portrait and landscape. For best image quality
            // we shouldn't divide by 2, but this will use more memory and require a larger memory
            // cache.
            final int longest = (height > width ? height : width) / 2;

            ImageCache.ImageCacheParams cacheParams =
                    new ImageCache.ImageCacheParams(this, IMAGE_CACHE_DIR);
            cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory

            // The ImageFetcher takes care of loading images into our ImageView children asynchronously
            mImageFetcher = new ImageFetcher(this, longest);
            mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);
            mImageFetcher.setImageFadeIn(false);

            // Set up ViewPager and backing adapter
            mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), Images.imageUrls.length);
            mPager = (ViewPager) findViewById(R.id.pager);
            mPager.setAdapter(mAdapter);
            mPager.setPageMargin((int) getResources().getDimension(R.dimen.horizontal_page_margin));
            mPager.setOffscreenPageLimit(2);

            // Set up activity to go full screen
            getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);

            // Enable some additional newer visibility and ActionBar features to create a more
            // immersive photo viewing experience
            if (Utils.hasHoneycomb()) {
                final ActionBar actionBar = getActionBar();

                // Hide title text and set home as up
                actionBar.setDisplayShowTitleEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);

                // Hide and show the ActionBar as the visibility changes
                mPager.setOnSystemUiVisibilityChangeListener(
                        new View.OnSystemUiVisibilityChangeListener() {
                            @Override
                            public void onSystemUiVisibilityChange(int vis) {
                                if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
                                    actionBar.hide();
                                } else {
                                    actionBar.show();
                                }
                            }
                        });

                // Start low profile mode and hide ActionBar
                mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
                actionBar.hide();
            }

            // Set the current item based on the extra passed in to this activity
            final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
            if (extraCurrentItem != -1) {
                mPager.setCurrentItem(extraCurrentItem);
            }
        }

        @Override
        public void onResume() {
            super.onResume();
            mImageFetcher.setExitTasksEarly(false);
        }

        @Override
        protected void onPause() {
            super.onPause();
            mImageFetcher.setExitTasksEarly(true);
            mImageFetcher.flushCache();
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            mImageFetcher.closeCache();
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case android.R.id.home:
                    NavUtils.navigateUpFromSameTask(this);
                    return true;
                case R.id.clear_cache:
                    mImageFetcher.clearCache();
                    Toast.makeText(
                            this, R.string.clear_cache_complete_toast,Toast.LENGTH_SHORT).show();
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main_menu, menu);
            return true;
        }

        /**
         * Called by the ViewPager child fragments to load images via the one ImageFetcher
         */
        public ImageFetcher getImageFetcher() {
            return mImageFetcher;
        }

        /**
         * The main adapter that backs the ViewPager. A subclass of FragmentStatePagerAdapter as there
         * could be a large number of items in the ViewPager and we don't want to retain them all in
         * memory at once but create/destroy them on the fly.
         */
        private class ImagePagerAdapter extends FragmentStatePagerAdapter {
            private final int mSize;

            public ImagePagerAdapter(FragmentManager fm, int size) {
                super(fm);
                mSize = size;
            }

            @Override
            public int getCount() {
                return mSize;
            }

            @Override
            public Fragment getItem(int position) {
                return ImageDetailFragment.newInstance(Images.imageUrls[position]);
            }


        }

        /**
         * Set on the ImageView in the ViewPager children fragments, to enable/disable low profile mode
         * when the ImageView is touched.
         */
        @TargetApi(VERSION_CODES.HONEYCOMB)
        @Override
        public void onClick(View v) {
            final int vis = mPager.getSystemUiVisibility();

            //Toast.makeText(this, "Value is: " + ,Toast.LENGTH_SHORT).show();


            if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
                mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            } else {
                mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
            }
        }


    }

正如你所看到的,我放了一个向我展示的Toast: 当Toast是Drawable时: enter image description here

当Toast是Bitmap时,有时会为同一个图像显示位图null(因为我在画廊中向后和向前滑动):

enter image description here

同一图像上的位图不为空:

enter image description here

我正在使用Android M 6.0的AVD图像

0 个答案:

没有答案