Java 重置/清除RecylerView
我正在使用Reformation/Picasso/Recyclerview的组合将图像加载到GridLayoutManager中。我有一个搜索栏,用户键入一个词来查询FlickR并根据搜索词填充结果 问题是我想假设一个用户可能想要重新搜索一个不同的术语。如果是这种情况,我希望清除RecyclerView,重新查询FlickR,然后将图像重新填充到RecyclerView中。似乎有很多活动,我相信有一种简单的方法可以实现:Java 重置/清除RecylerView,java,android,xml,android-recyclerview,Java,Android,Xml,Android Recyclerview,我正在使用Reformation/Picasso/Recyclerview的组合将图像加载到GridLayoutManager中。我有一个搜索栏,用户键入一个词来查询FlickR并根据搜索词填充结果 问题是我想假设一个用户可能想要重新搜索一个不同的术语。如果是这种情况,我希望清除RecyclerView,重新查询FlickR,然后将图像重新填充到RecyclerView中。似乎有很多活动,我相信有一种简单的方法可以实现: public class NewImageActivity extends
public class NewImageActivity extends AppCompatActivity {
private SearchView mSearchView;
private RecyclerView mImageResults;
private RecyclerView.Adapter mImageResultsAdapter;
private ArrayList<Photo> mPhotoArray;
private ArrayList<String> mPhotoURLS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_image);
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
mImageResults = (RecyclerView) findViewById(R.id.flickr_image_results_view);
GridLayoutManager glm = new GridLayoutManager(this, 2);
glm.setOrientation(LinearLayoutManager.VERTICAL);
mImageResults.setLayoutManager(glm);
mImageResults.setItemAnimator(new DefaultItemAnimator());
mImageResultsAdapter = new MyAdapter(mPhotoURLS);
mImageResults.setAdapter(mImageResultsAdapter);
int spanCount = 2; // 3 columns
int spacing = 25; // 50px
boolean includeEdge = false;
mImageResults.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
mPhotoURLS = new ArrayList<>();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
// Retrieve the SearchView and plug it into SearchManager
MenuItem searchItem = menu.findItem(R.id.search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchItem.expandActionView();
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(getApplicationContext(), "Open", Toast.LENGTH_LONG).show();
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
Toast.makeText(getApplicationContext(), "Back_Press", Toast.LENGTH_LONG).show();
finish();
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
//the urls to populate the Recyclerview; URLs dumped into Picasso
mPhotoURLS.clear();
mImageResultsAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_LONG).show();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.flickr.com/services/rest/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<Flicker> call = apiInterface.getImages(query);
call.enqueue(new Callback<Flicker>() {
@Override
public void onResponse(Call<Flicker> call, Response<Flicker> response) {
Log.v("RESPONSE_CALLED", "ON_RESPONSE_CALLED");
String didItWork = String.valueOf(response.isSuccessful());
Log.v("SUCCESS?", didItWork);
Log.v("RESPONSE_CODE", String.valueOf(response.code()));
Flicker testResponse = response.body();
Log.v("RESPONSE_BODY", "response:" + testResponse);
String total = response.body().getPhotos().getTotal().toString();
Log.v("Total", total);
List<Photo> photoResults = response.body().getPhotos().getPhoto();
int numberOfPages = response.body().getPhotos().getPages();
for (int i = 0; i < numberOfPages; i++) {
for (Photo photo : photoResults) {
if (photo.getUrl_m() != null) {
String photoURL = photo.getUrl_m();
Log.v("PHOTO_URL:", photoURL);
mPhotoURLS.add(photoURL);
mImageResultsAdapter.notifyDataSetChanged();
}
}
}
}
@Override
public void onFailure(Call<Flicker> call, Throwable t) {
}
});
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
protected ImageView mResultImage;
public ViewHolder(View v) {
super(v);
mResultImage = (ImageView) v.findViewById(R.id.flickr_individual_image);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<String> mDataSet) {
mPhotoURLS = mDataSet;
}
// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.grid_item, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
//The OutOfBoundsException is pointing here
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.v("ON_BIND", "ON_BINDVIEWHOLDER CALLED");
String urlForPhoto = mPhotoURLS.get(position);
Picasso.with(getApplicationContext())
.load(urlForPhoto)
.placeholder( R.drawable.progress_animation )
.into(holder.mResultImage);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mPhotoURLS.size();
}
}
public void clearData() {
int size = this.mPhotoURLS.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.mPhotoURLS.remove(0);
}
mImageResultsAdapter.notifyItemRangeRemoved(0, size);
}
}
public interface ApiInterface {
@GET("?method=flickr.photos.search&api_key=1c448390199c03a6f2d436c40defd90e&format=json&nojsoncallback=1&extras=url_m")
Call<Flicker> getImages(@Query("text") String query);
}
公共类NewImageActivity扩展了AppCompatActivity{
私有搜索视图;
私人RecyclerView mImageResults;
私有RecyclerView.Adapter mImageResultsAdapter;
私人ArrayList mPhotoArray;
私人ArrayList酒店;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u new\u image);
如果(getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
mImageResults=(RecyclerView)findViewById(R.id.flickr\u image\u results\u视图);
GridLayoutManager glm=新的GridLayoutManager(这个,2);
glm.setOrientation(LinearLayoutManager.VERTICAL);
设置布局管理器(glm);
setItemAnimator(新的DefaultItemAnimator());
mImageResultsAdapter=新的MyAdapter(mPhotoURLS);
setAdapter(mImageResultsAdapter);
int spanCount=2;//3列
int间距=25;//50px
布尔includeEdge=false;
mImageResults.addItemDecoration(新的GridSpacingItemDecoration(spanCount、spacing、includeEdge));
mPhotoURLS=newarraylist();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(R.menu.menu\u搜索,菜单);
//检索SearchView并将其插入SearchManager
MenuItem searchItem=menu.findItem(R.id.search);
最终SearchView SearchView=(SearchView)MenuItemCompat.getActionView(searchItem);
searchItem.expandActionView();
MenuItemCompat.setOnActionExpandListener(searchItem,新MenuItemCompat.OnActionExpandListener()){
@凌驾
公共布尔值onMenuItemActionExpand(MenuItem项){
Toast.makeText(getApplicationContext(),“Open”,Toast.LENGTH_LONG.show();
返回true;
}
@凌驾
公共布尔值onMenuItemActionCollapse(MenuItem项){
Toast.makeText(getApplicationContext(),“后退”,Toast.LENGTH.show();
完成();
返回true;
}
});
searchView.setOnQueryTextListener(新的searchView.OnQueryTextListener(){
@凌驾
公共布尔值onQueryTextSubmit(字符串查询){
视图=getCurrentFocus();
如果(视图!=null){
InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT\u方法\u服务);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
}
//填充Recyclerview的URL;转储到毕加索的URL
mPhotoURLS.clear();
mImageResultsAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),query,Toast.LENGTH_LONG.show();
HttpLoggingInterceptor拦截器=新的HttpLoggingInterceptor();
拦截器.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient客户端=新建OkHttpClient.Builder().addInterceptor(拦截器).build();
改装改装=新改装.Builder()
.baseUrl(“https://api.flickr.com/services/rest/")
.客户(客户)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface ApiInterface=reformation.create(ApiInterface.class);
Call Call=apinterface.getImages(查询);
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
Log.v(“调用响应”、“调用响应”);
String didItWork=String.valueOf(response.issusccessful());
Log.v(“成功?”,didItWork);
Log.v(“RESPONSE_CODE”,String.valueOf(RESPONSE.CODE());
闪烁测试响应=response.body();
Log.v(“响应\正文”,“响应:+testResponse”);
字符串总数=response.body().getPhotos().getTotal().toString();
对数v(“总计”,总计);
List photoResults=response.body().getPhotos().getPhoto();
int numberOfPages=response.body().getPhotos().getPages();
对于(int i=0;i mPhotoURLS.clear();
for (int i = 0; i < numberOfPages; i++) {
for (Photo photo : photoResults) {
if (photo.getUrl_m() != null) {
String photoURL = photo.getUrl_m();
Log.v("PHOTO_URL:", photoURL);
mPhotoURLS.add(photoURL);
}
}
}
mImageResultsAdapter.notifyDataSetChanged();