我有一个recyclerview和一个listview。 recyclerview的方向是水平的,固定在textview之后的屏幕顶部。 listview内部有另一个recyclerview。因此,当我单击最固定的recyclerview中的一项时,我想移动到listview的相同位置(可能正在使用smoothScrollToPosition)。我在网上搜索了所有内容,但找不到任何解决方案。有人可以帮我吗?预先感谢您的努力。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
Intent mIntent = getIntent();
String title = mIntent.getStringExtra("title");
mRetailer = mIntent.getStringExtra("retailer");
setTitle(title.toUpperCase());
headingTxt = (TextView) findViewById(R.id.txt_heading); //heading text
subHeadingTxt = (TextView) findViewById(R.id.txt_sub_heading); //number of categories text
}
mCategories = new ArrayList<>();
mCategories.clear();
HorizontalScrollView hr = (HorizontalScrollView) findViewById(R.id.horizontal_scroll_categories);
hr.setScrollBarSize(10);
mRecyclerView = (RecyclerView) findViewById(R.id.categories_recyclerview);
mRecyclerView.setScrollBarSize(10);
//====== For category Lists ========
categoryAdapter = new CategoryListViewAdapter(mRetailer);
mListView = (ListView)findViewById(R.id.category_detail_listview);
mListView.setDivider(null);
mListView.setDividerHeight(0);
mListView.setAdapter(categoryAdapter);
OkHttpClient client = new OkHttpClient();
String url = "http://serveraddress/MerchApp/web/get_all_category.php";
final Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
String cateName, catePName;
int cateId, cateUid, cateDepth;
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
final String mResponse = response.body().string();
CategoryActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
JSONArray jsonArray = null;
try {
JSONObject jsonObject = new JSONObject(mResponse);
jsonArray = jsonObject.getJSONArray("categories"); //JSONArray(mResponse);
JSONObject ob;
for(int i = 0; i<jsonArray.length(); i++){
ob = jsonArray.getJSONObject(i);
cateId=ob.getInt("cate_id");
cateName=ob.getString("cate_name");
cateUid=ob.getInt("cate_pid");
cateDepth=ob.getInt("cate_depth");
if(cateDepth == 0) {
mCategories.add(new Categories(cateId, cateName, R.drawable.ic_music_note_black_35dp));
CategoryInfo cateInfo=new CategoryInfo(cateId, cateName, "",CategoryActivity.this);
categoryAdapter.addItem(cateInfo);
categoryAdapter.notifyDataSetChanged();
}
}
// set 2depth(sub) category
for (int i = 0; i < jsonArray.length(); i++) { //
JSONObject subCateOb =jsonArray.getJSONObject(i);
cateId=subCateOb.getInt("cate_id");
cateName=subCateOb.getString("cate_name");
cateUid=subCateOb.getInt("cate_pid");
cateDepth=subCateOb.getInt("cate_depth");
catePName=subCateOb.getString("cate_pname");
if(cateDepth != 0) {
SubcategoryInfo subCateInfo=new SubcategoryInfo(cateId, cateUid, cateName, catePName,"");
categoryAdapter.categoryMap.get(cateUid).getSubCateAdapter().addSubCateItem(subCateInfo);
categoryAdapter.categoryMap.get(cateUid).getSubCateAdapter().notifyDataSetChanged();
}
}
setHeader(); // set the top header categories
} catch (Exception e) {
e.printStackTrace();
LOGGER.info("!# Request error!!!!! : {}", e.getMessage());
//return "serverError";
}
}
});
setCategory(); //set the lower categories
}
}
});
}
public void setHeader(){
mAdapter = new CategoriesRecyclerViewAdapter(CategoryActivity.this, mCategories);
mRecyclerView.setLayoutManager(new GridLayoutManager(CategoryActivity.this, mCategories.size()));
mRecyclerView.setAdapter(mAdapter);
subHeadingTxt.setText(mAdapter.getItemCount()+" Categories");
}
public void setCategory(){
categoryAdapter = new CategoryListViewAdapter(mRetailer);
mListView.setAdapter(categoryAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.retailers_search_menu, menu);
MenuItem item = menu.findItem(R.id.search_retailers);
final SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
categoryAdapter.getFilter().filter(s);
System.out.println("Submit Executed" + s);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
System.out.println("Changed Executed" + s);
categoryAdapter.getFilter().filter(s);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
和自定义RecyclerView适配器如下所示:
public class CategoriesRecyclerViewAdapter extends
RecyclerView.Adapter<CategoriesRecyclerViewAdapter.MyViewHolder>
implements Filterable {
private Context context;
private ArrayList<Categories> mCategories;
private ArrayList<Categories> mFilteredCategories;
public CategoriesRecyclerViewAdapter(Context context,
ArrayList<Categories> mCategory) {
mCategories = mCategory;
mFilteredCategories = mCategory;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
View view;
LayoutInflater mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.category_header_thumbnail, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int position) {
myViewHolder.mCategoryThumbnail.setImageResource(mCategories.get(position).getCategoryThumbnail());
}
@Override
public int getItemCount() {
return mCategories.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView mCategoryThumbnail;
CardView mCategoryCardView;
public MyViewHolder(View itemView) {
super(itemView);
mCategoryThumbnail = (ImageView) itemView.findViewById(R.id.categories_img);
mCategoryCardView = (CardView) itemView.findViewById(R.id.categories_card);
}
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) { charSequence.length());
FilterResults results = new FilterResults();
// if there is nothing to filter on, return the original List of Retailers;
if(charSequence == null || charSequence.length() == 0){
results.values = mFilteredCategories;
results.count = mFilteredCategories.size();
}else {
List<Categories> filteredResultsData = new ArrayList<Categories>();
for(Categories retailer: mFilteredCategories){
if(retailer.getCategoryName().toUpperCase().startsWith(charSequence.toString().toUpperCase())){
filteredResultsData.add(retailer);
}
}
results.values = filteredResultsData;
results.count = filteredResultsData.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mCategories = (ArrayList<Categories>) results.values;
notifyDataSetChanged();
}
};
}
}
答案 0 :(得分:0)
在您的课程中实现onItemClickListener。 在这种实现的方法中,您将获得recyclerview项目的位置。
示例
Class example implements CategoriesRecyclerViewAdapter.OnItemClickListener{
Listview listView;//your listview
ArrayList alListview;//arraylist for your listview
@Override
public void onItemclick(int position){
if(alListview.size()>=position)
listView.smoothScrollToPosition(position);
}
}
您的适配器类
public class CategoriesRecyclerViewAdapter extends
RecyclerView.Adapter<CategoriesRecyclerViewAdapter.MyViewHolder>
implements Filterable {
private Context context;
private ArrayList<Categories> mCategories;
private ArrayList<Categories> mFilteredCategories;
private PetrolManFilterAdapter.OnItemClickListener listener;
public CategoriesRecyclerViewAdapter(Context context,
ArrayList<Categories> mCategory, PetrolManFilterAdapter.OnItemClickListener clickListener) {
mCategories = mCategory;
mFilteredCategories = mCategory;
this.context = context;
listener = clickListener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
View view;
LayoutInflater mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.category_header_thumbnail, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int position) {
myViewHolder.mCategoryThumbnail.setImageResource(mCategories.get(position).getCategoryThumbnail());
myViewHolder.mCategoryThumbnail.setOnClickListener(v -> {
listener.onItemclick(position);
});
}
public Categories getItemAtPosition(int position) {
return arrayList.get(position);
}
@Override
public int getItemCount() {
return mCategories.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView mCategoryThumbnail;
CardView mCategoryCardView;
public MyViewHolder(View itemView) {
super(itemView);
mCategoryThumbnail = (ImageView) itemView.findViewById(R.id.categories_img);
mCategoryCardView = (CardView) itemView.findViewById(R.id.categories_card);
}
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) { charSequence.length());
FilterResults results = new FilterResults();
// if there is nothing to filter on, return the original List of Retailers;
if(charSequence == null || charSequence.length() == 0){
results.values = mFilteredCategories;
results.count = mFilteredCategories.size();
}else {
List<Categories> filteredResultsData = new ArrayList<Categories>();
for(Categories retailer: mFilteredCategories){
if(retailer.getCategoryName().toUpperCase().startsWith(charSequence.toString().toUpperCase())){
filteredResultsData.add(retailer);
}
}
results.values = filteredResultsData;
results.count = filteredResultsData.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mCategories = (ArrayList<Categories>) results.values;
notifyDataSetChanged();
}
};
}
public interface OnItemClickListener {
void onItemclick(int position);
}
}
答案 1 :(得分:0)
非常感谢您的参与,但我自己找到了解决方案。如果外面有人遇到相同或相似的问题,这就是我的做法。 首先,我创建了一个名为 OnRecyclerViewItemClickListener 的recyclerview项目点击侦听器界面,如下所示
import android.view.View;
public interface OnRecyclerViewItemClickListener {
void onItemClick(int position, View view);
}
使用此接口,我们可以在 Activity 或 Fragment 中实现它。这将覆盖我的活动中的itemclick方法。
然后,将以下内容添加到我的CategoriesRecyclerViewAdapter中。
....
private OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
}
...
接下来,在onBindViewHolder方法中,我以这种方式声明了布局setOnclicklistener。
...
myViewHolder.mCategoryThumbnail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onRecyclerViewItemClickListener != null) {
onRecyclerViewItemClickListener.onItemClick(position, v);
}
}
});
...
要获取RecyclerView单击项目的位置,我将标签设置为CategoryActivity类中的layout,如下所示:
...
@Override
public void onItemClick(int position, View v) {
Categories categories = (Categories) mListView.getTag();
switch (v.getId()){
case R.id.categories_img:
mListView.smoothScrollToPosition(position);
break;
}
}
...
最后,我将我的onRecyclerViewItemClickListener设置为CategoryActivity类中的适配器,该类实际上是在我的类的setHeader方法中找到的,如下所示。 (第5行是添加的代码)
1 ...
2 public void setHeader(){
3 mAdapter = new CategoriesRecyclerViewAdapter(CategoryActivity.this, mCategories);
4 mRecyclerView.setLayoutManager(new GridLayoutManager(CategoryActivity.this, mCategories.size()));
5 mAdapter.setOnRecyclerViewItemClickListener(this);
6 mRecyclerView.setAdapter(mAdapter);
7 subHeadingTxt.setText(mAdapter.getItemCount()+" Categories");
8 }
9 ...
仅此而已。对我来说效果很好。我希望它也对您有用,并节省您的时间。
干杯。~~
已更新:- 我忘了提到这一重要说明了。...不要忘记实现OnRecyclerViewItemClickListener接口。
public class CategoryActivity extends AppCompatActivity implements OnRecyclerViewItemClickListener {...}