Android; setAdapter working/not 工作取决于 android 支持库版本

Android; setAdapter working/not working depending on android support library version

我目前有一个小型旧版应用程序,它以不同的视图显示当前相册及其图像。因此,视图一会显示相册,选择相册后,它会打开显示所选相册图像的视图。

当应用程序 运行 android 支持库版本 18 时,应用程序工作正常。但是当我将版本升级到 19 或更高版本时,应用程序停止正常工作。它打开了应该显示相册但实际上并没有显示相册的视图。请参阅 post 末尾的图像来说明问题。

我已将问题定位到以下代码行。

mBucketAdapter = new BucketGridAdapter(getActivity(), 0, buffer, false);
mGridView.setAdapter(mBucketAdapter); <---------

BucketGridAdapter 是扩展 ArrayAdapter<BucketEntry> 的自定义 class。如您所见,class BucketGridAdapter 覆盖了函数 getView。此函数在 android 支持库版本 18 上被调用,但是当我升级版本时它不再被调用。

我注意到,当我注释掉 mGridView.setAdapter(mBucketAdapter); 行时,它显示的行为与升级 android 支持库版本时的行为相同。 (空网格)

问题是我无法在这行代码 mGridView.setAdapter(mBucketAdapter) 和函数 getView() 之间进行调试,所以我不知道为什么 getView 函数没有被调用android 支持库的更高版本。

我很乐意在这个问题上得到一些帮助。如果您遗漏任何信息,请直接说出来,我会添加。

编辑:请注意 get count 在 android 支持库版本 19 和更高版本 上具有值,因此应调用 getView 函数.

mBucketAdapter = new BucketGridAdapter(getActivity(), 0, buffer, false);
int count = mBucketAdapter.getCount(); // <-- count = 8
mGridView.setAdapter(mBucketAdapter);

请参阅下面的 BucketImageFragment class:

package mediachooser.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
import com.synconset.FakeR;
import mediachooser.BucketEntry;
import mediachooser.MediaChooserConstants;
import mediachooser.activity.HomeFragmentActivity;
import mediachooser.adapter.BucketGridAdapter;

import java.util.ArrayList;

public class BucketImageFragment extends Fragment{

    // The indices should match the following projections.
    private final int INDEX_BUCKET_ID     = 0;
    private final int INDEX_BUCKET_NAME   = 1;
    private final int INDEX_BUCKET_URL    = 2;

    private static final String[] PROJECTION_BUCKET = {
        ImageColumns.BUCKET_ID,
        ImageColumns.BUCKET_DISPLAY_NAME,
        ImageColumns.DATA};

    private View mView;
    private GridView mGridView;
    private BucketGridAdapter mBucketAdapter;

    private Cursor mCursor;



    public BucketImageFragment(){
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if(mView == null){
            mView     = inflater.inflate(getRLayoutId("view_grid_layout_media_chooser"), container, false);
            mGridView = (GridView)mView.findViewById(getRIntId("gridViewFromMediaChooser"));
            init();
        }else{
            ((ViewGroup) mView.getParent()).removeView(mView);
            if(mBucketAdapter == null){
                Toast.makeText(getActivity(), getActivity().getString(getRStringId("no_media_file_available")), Toast.LENGTH_SHORT).show();
            }
        }
        return mView;
    }


    private void init(){
        final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
         mCursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, PROJECTION_BUCKET, null, null, orderBy + " DESC");
        ArrayList<BucketEntry> buffer = new ArrayList<BucketEntry>();
        try {
            while (mCursor.moveToNext()) {
                BucketEntry entry = new BucketEntry(
                        mCursor.getInt(INDEX_BUCKET_ID),
                        mCursor.getString(INDEX_BUCKET_NAME),mCursor.getString(INDEX_BUCKET_URL));

                if (! buffer.contains(entry)) {
                    buffer.add(entry);
                }
            }

            if(mCursor.getCount() > 0){
                mBucketAdapter = new BucketGridAdapter(getActivity(), 0, buffer, false);
                mGridView.setAdapter(mBucketAdapter); <------- THIS LINE
            }else{
                Toast.makeText(getActivity(), getActivity().getString(getRStringId("no_media_file_available")), Toast.LENGTH_SHORT).show();
            }

            mGridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> adapter, View view,
                        int position, long id) {

                    BucketEntry bucketEntry  = (BucketEntry)adapter.getItemAtPosition(position);
                    Intent selectImageIntent = new Intent(getActivity(),HomeFragmentActivity.class);
                    selectImageIntent.putExtra("name", bucketEntry.bucketName);
                    selectImageIntent.putExtra("image", true);
                    selectImageIntent.putExtra("isFromBucket", true);
                    getActivity().startActivityForResult(selectImageIntent, MediaChooserConstants.BUCKET_SELECT_IMAGE_CODE);
                }
            });

        } finally {
            mCursor.close();
        }
    }

    public BucketGridAdapter getAdapter() {
        return  mBucketAdapter;
    }


    public int getRStringId(String resourceId){
        return FakeR.getId(getActivity(), "string", resourceId);
    }

    public int getRIntId(String resourceId){
        return FakeR.getId(getActivity(), "id", resourceId);
    }

    public int getRColorId(String resourceId){
        return FakeR.getId(getActivity(), "color", resourceId);
    }

    public int getRDrawableId(String resourceId){
        return FakeR.getId(getActivity(), "drawable", resourceId);
    }
    public int getRLayoutId(String resourceId){
        return FakeR.getId(getActivity(), "layout", resourceId);
    }


}

见下文 BucketGridAdapter class。

package mediachooser.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.synconset.FakeR;
import mediachooser.BucketEntry;
import mediachooser.MediaChooserConstants;
import mediachooser.async.ImageLoadAsync;
import mediachooser.async.MediaAsync;

import java.util.ArrayList;

public class BucketGridAdapter extends ArrayAdapter<BucketEntry> {

//  public BucketVideoFragment bucketVideoFragment;

    private Context mContext;
    private ArrayList<BucketEntry> mBucketEntryList;
    private boolean mIsFromVideo;
    private int mWidth;
    LayoutInflater viewInflater;


    public BucketGridAdapter(Context context, int resource, ArrayList<BucketEntry> categories, boolean isFromVideo) {
        super(context, resource, categories);
        mBucketEntryList = categories;
        mContext         = context;
        mIsFromVideo     = isFromVideo;
        viewInflater = LayoutInflater.from(mContext);
    }

    public int getCount() {
        return mBucketEntryList.size();
    }

    @Override
    public BucketEntry getItem(int position) {
        return mBucketEntryList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void addLatestEntry(String url) {
        int count = mBucketEntryList.size();
        boolean success = false;
        for(int i = 0; i< count; i++){
            if(mBucketEntryList.get(i).bucketName.equals(MediaChooserConstants.folderName)){
                mBucketEntryList.get(i).bucketUrl = url;
                success = true;
                break;
            }
        }

        if(!success){
            BucketEntry latestBucketEntry = new BucketEntry(0, MediaChooserConstants.folderName, url);
            mBucketEntryList.add(0, latestBucketEntry);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        if (convertView == null) {

            mWidth = mContext.getResources().getDisplayMetrics().widthPixels;

            convertView  = viewInflater.inflate(getRLayoutId("view_grid_bucket_item_media_chooser"), parent, false);

            holder = new ViewHolder();
            holder.imageView    = (ImageView) convertView.findViewById(getRIntId("imageViewFromMediaChooserBucketRowView"));
            holder.nameTextView = (TextView) convertView.findViewById(getRIntId("nameTextViewFromMediaChooserBucketRowView"));

            convertView.setTag(holder);

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

        FrameLayout.LayoutParams imageParams = (FrameLayout.LayoutParams) holder.imageView.getLayoutParams();
        imageParams.width  = mWidth/3;
        imageParams.height = mWidth/3;

        holder.imageView.setLayoutParams(imageParams);

        if(mIsFromVideo){
//          new VideoLoadAsync(bucketVideoFragment, holder.imageView, false, mWidth/2).executeOnExecutor(MediaAsync.THREAD_POOL_EXECUTOR, mBucketEntryList.get(position).bucketUrl.toString());

        }else{
            ImageLoadAsync loadAsync = new ImageLoadAsync(mContext, holder.imageView, mWidth/2);
            loadAsync.executeOnExecutor(MediaAsync.THREAD_POOL_EXECUTOR, mBucketEntryList.get(position).bucketUrl);
        }

        holder.nameTextView.setText(mBucketEntryList.get(position).bucketName );
        return convertView;
    }

    class ViewHolder {
        ImageView imageView;
        TextView nameTextView;
    }

    public int getRStringId(String resourceId){
        return FakeR.getId(mContext, "string", resourceId);
    }

    public int getRIntId(String resourceId){
        return FakeR.getId(mContext, "id", resourceId);
    }

    public int getRColorId(String resourceId){
        return FakeR.getId(mContext, "color", resourceId);
    }

    public int getRDrawableId(String resourceId){
        return FakeR.getId(mContext, "drawable", resourceId);
    }
    public int getRLayoutId(String resourceId){
        return FakeR.getId(mContext, "layout", resourceId);
    }

}

见下文BucketEntryclass

package mediachooser;

public class BucketEntry {
    public String bucketName;
    public int bucketId;
    public String bucketUrl = null;

    public BucketEntry(int id, String name, String url) {
        bucketId = id;
        bucketName = ensureNotNull(name);
        bucketUrl = url;
    }

    @Override
    public int hashCode() {
        return bucketId;
    }

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof BucketEntry)) return false;
        BucketEntry entry = (BucketEntry) object;
        return bucketId == entry.bucketId;
    }

    public static String ensureNotNull(String value) {
        return value == null ? "" : value;
    }
}

参见下面的 view_grid_layout_media_chooser.xml 视图

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_height="fill_parent"
              android:layout_width="fill_parent"
              android:orientation="vertical" > <!-- android:background="@drawable/image_bg" -->

    <GridView
            android:id="@+id/gridViewFromMediaChooser"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:columnWidth="0dip"
            android:fadingEdgeLength="10dip"
            android:fastScrollEnabled="true"
            android:gravity="center"
            android:horizontalSpacing="2dip"
            android:numColumns="3"
            android:requiresFadingEdge="vertical"
            android:scrollingCache="true"
            android:stretchMode="columnWidth"
            android:verticalSpacing="2dip" />

</LinearLayout>

见下方 view_grid_bucket_item_media_chooser.xml 视图

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <mediachooser.SquareImageView
        android:id="@+id/imageViewFromMediaChooserBucketRowView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@null"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_loading" />

    <TextView
        android:id="@+id/nameTextViewFromMediaChooserBucketRowView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#88666666"
        android:ellipsize="end"
        android:gravity="center"
        android:maxLines="1"
        android:text="@string/video"
        android:textColor="@android:color/white"
        android:textSize="14sp" />

</FrameLayout>

插图图片:

工作:

不工作:

好的,在寻找了数小时和数小时......更多小时后,我们发现了一个小视图 XML 设置,该设置扰乱了其中一个视图的可见性。

android:visibility="gone"

似乎这个 XML 设置被 Android 支持库版本 18 忽略了,但是当它升级到更高版本时,设置被使用了。

当视图被隐藏时,无论是通过上面的设置还是错误的 width en height 设置,android 都不会开始编写视图。或者换句话说;使用 getView 函数,在我们使用 19 或更高版本的 Android 支持库时,它没有执行。

希望对大家有所帮助。