在Android中的Recyclerview中滚动时的图像消失

时间:2016-12-13 16:38:54

标签: android android-recyclerview android-imageview picasso android-viewholder

我是Android的新手,并试图通过网址按钮点击加载图片。图像正在加载,但是当我向下滚动我的活动并尝试再次向上滚动时,图像会自动消失。

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder>  {

ArrayList<String> urls;
Context context;


public ImageAdapter(Context context,ArrayList<String> urls) {
    this.urls = urls;
    this.context=context;
}
@Override
public ImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewimage, parent, false);
    return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.imageButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String pos = urls.get(position);
            Log.d("Pos Value", pos);
            holder.setIsRecyclable(false);

            if("".equals(holder)) {
                holder.imageView.setVisibility(View.GONE);
                holder.imageView.setImageDrawable(null);
            }
            else {
                holder.imageView.setVisibility(View.VISIBLE);

                Picasso.with(holder.imageView.getContext()).cancelRequest(holder.imageView);
                Picasso.with(holder.imageView.getContext()).load(pos).memoryPolicy(MemoryPolicy.NO_CACHE).placeholder(R.drawable.image).resize(100,100).into(holder.imageView);
                holder.imageView.setImageURI(null);
            }
        }
    });
}
@Override
public int getItemCount() {
    return urls.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
    public ImageView imageView;
    public ImageButton imageButton;
    public ViewHolder(View itemView) {
        super(itemView);
        imageView = (ImageView) itemView.findViewById(R.id.imageView);
        imageButton = (ImageButton) itemView.findViewById(R.id.imageButton);
    }
}
}

主要活动

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    recyclerView=(RecyclerView)findViewById(R.id.recycleImage);
    layoutManager=new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    addItemstoArrayList();
    ImageAdapter imageAdapter=new ImageAdapter(getApplicationContext(),urls);
    imageAdapter.notifyDataSetChanged();
    recyclerView.setAdapter(imageAdapter);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }



}
public void addItemstoArrayList()
{
    urls=new ArrayList<>();
    urls.add("http://kingofwallpapers.com/random-image/random-image-005.jpg");
    urls.add("http://archives.frederatorblogs.com/random/files/2008/04/b-corrupted-by-random-noise-bit-error-rate0020.gif");
    urls.add("https://lh3.ggpht.com/VnSav7pXcExlls8O5xV3m7cN2M3UGHZLkkHkvZtwEBtrsPCXzRtOGlzvg6GzYCV-9PAS=w300");
    urls.add("http://schooltutoring.com/help/wp-content/uploads/sites/2/2014/07/Math-Review-of-Random-Numbers.jpg");
    urls.add("http://static.tumblr.com/b5e9590d4f2aa32199cf5ba25105838a/8va8xfq/nlDnpamkw/tumblr_static_64tfx6f0lesk4ss4c8g8wcos0.png");
    urls.add("https://storage.googleapis.com/imgfave/image_cache/1359429986261769.jpg");
    urls.add("http://images2.fanpop.com/image/photos/8800000/Cool-Pic-s-random-8889999-437-320.jpg");
    urls.add("http://images6.fanpop.com/image/photos/35500000/Cool-pics-random-35514813-500-313.jpg");
    urls.add("http://s8.favim.com/orig/72/beautiful-photography-random-tumblr-Favim.com-675117.jpg");
    urls.add("http://s8.favim.com/orig/72/beautiful-photography-random-tumblr-Favim.com-672024.jpg");
}
}

1 个答案:

答案 0 :(得分:0)

试试这个:

ImageAdapter +更新的Viewholder

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {

ArrayList<String> urls;
Context context;


public ImageAdapter(Context context, ArrayList<String> urls) {
    this.urls = urls;
    this.context = context;
}

@Override
public ImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_viewholder, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    String pos = urls.get(holder.getAdapterPosition());
    Log.i("Pos Value", pos);
    holder.onBindViewHolder(pos);
}

@Override
public int getItemCount() {
    return urls.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public ImageView imageView;
    public Button button;
    boolean clicked = false;

    public ViewHolder(View itemView) {
        super(itemView);
        imageView = (ImageView) itemView.findViewById(R.id.iv_main);
        button = (Button) itemView.findViewById(R.id.ib_main);
        button.setText("click");
    }

    public void onBindViewHolder(String url) {

        if (clicked) {
            Picasso.with(itemView.getContext())
                    .load(url)
                    .placeholder(R.mipmap.ic_launcher)
                    .resize(100, 100)
                    .into(imageView);
        } else {
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clicked = true;
                    Picasso.with(itemView.getContext())
                            .load(urls.get(getAdapterPosition()))
                            .placeholder(R.mipmap.ic_launcher)
                            .resize(100, 100)
                            .into(imageView);
                }
            });
        }
    }
}
}

MainActivity + Picasso全局错误侦听器(可选)

public class MainActivity extends AppCompatActivity {

private ArrayList<String> urls;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    populate();
    setUpRecyclerView();
    setPicassoErrorListener();
}

public void setPicassoErrorListener() {
    Picasso.Builder picassoBuilder = new Picasso.Builder(this);

    picassoBuilder.listener(new Picasso.Listener() {
        @Override
        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
            Log.e("PICASSO", uri.toString(), exception);
        }
    });

    // Picasso.Builder creates the Picasso object to do the actual requests
    Picasso picasso = picassoBuilder.build();

    try {
        Picasso.setSingletonInstance(picasso);
    } catch (IllegalStateException ignored) {
        // Picasso instance was already set
        // cannot set it after Picasso.with(Context) was already in use
    }


}

private void setUpRecyclerView() {
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    ImageAdapter imageAdapter = new ImageAdapter(getApplicationContext(), urls);
    imageAdapter.notifyDataSetChanged();
    recyclerView.setAdapter(imageAdapter);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
}

public void populate() {
    urls = new ArrayList<>();
    urls.add("http://kingofwallpapers.com/random-image/random-image-005.jpg");
    urls.add("http://archives.frederatorblogs.com/random/files/2008/04/b-corrupted-by-random-noise-bit-error-rate0020.gif");
    urls.add("https://lh3.ggpht.com/VnSav7pXcExlls8O5xV3m7cN2M3UGHZLkkHkvZtwEBtrsPCXzRtOGlzvg6GzYCV-9PAS=w300");
    urls.add("http://schooltutoring.com/help/wp-content/uploads/sites/2/2014/07/Math-Review-of-Random-Numbers.jpg");
    urls.add("http://static.tumblr.com/b5e9590d4f2aa32199cf5ba25105838a/8va8xfq/nlDnpamkw/tumblr_static_64tfx6f0lesk4ss4c8g8wcos0.png");
    urls.add("https://storage.googleapis.com/imgfave/image_cache/1359429986261769.jpg");
    urls.add("http://images2.fanpop.com/image/photos/8800000/Cool-Pic-s-random-8889999-437-320.jpg");
    urls.add("http://images6.fanpop.com/image/photos/35500000/Cool-pics-random-35514813-500-313.jpg");
    urls.add("http://s8.favim.com/orig/72/beautiful-photography-random-tumblr-Favim.com-675117.jpg");
    urls.add("http://s8.favim.com/orig/72/beautiful-photography-random-tumblr-Favim.com-672024.jpg");
}

}

image_viewholder.xml

<?xml version="1.0" encoding="utf-8"?>
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
    android:id="@+id/iv_main"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"/>
<Button
    android:id="@+id/ib_main"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="iblocks.co.uk.imageadapter">

<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">


    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

希望它有助于帮助chum