簡體   English   中英

處理多種類型的視圖單擊RecyclerView

[英]Handle Multiple Type Views Click in RecyclerView

RecyclerView中顯示了3部分數據:1.產品2.配方3.收集

當我嘗試在一個RecyclerView中顯示多個視圖類型時。 是的,這是工作。 它可以顯示所有這些。 但是,當我嘗試根據其位置處理點擊列表時,我面臨一些困難。 它始終顯示java.lang.IndexOutOfBoundsException。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        List<BaseModel> baseModels = new ArrayList<>();

        Product product = new Product();
        product.setTitle("BBQ Chicken");
        Product product2 = new Product();
        product2.setTitle("BBQ Chicken 2");
        baseModels.add(product);
        baseModels.add(product2);

        Recipe recipe = new Recipe();
        recipe.setTitle("Pulled Pork");
        Recipe recipe2 = new Recipe();
        recipe2.setTitle("Pulled Pork 2");
        baseModels.add(recipe);
        baseModels.add(recipe2);

        Collection collection = new Collection();
        collection.setTitle("Recipe Collection");
        Collection collection2 = new Collection();
        collection2.setTitle("Recipe Collection 2");
        baseModels.add(collection);
        baseModels.add(collection2);

        RecyclerView list = (RecyclerView) findViewById(R.id.list);
        list.setLayoutManager(new LinearLayoutManager(this));
        list.setAdapter(new InventoryAdapter(baseModels, this));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

InventoryAdapter.java

public class InventoryAdapter extends RecyclerView.Adapter<BaseViewHolder> {

    private List<? extends BaseModel> mList;
    private LayoutInflater mInflator;

    public InventoryAdapter(List<? extends BaseModel> list, Context context) {
        this.mList = list;
        this.mInflator = LayoutInflater.from(context);
    }

    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ViewType.COLLECTION_TYPE:
                return new CollectionHolder(mInflator.inflate(R.layout.type_collection, parent,false));
            case ViewType.PRODUCT:
                return new ProductHolder(mInflator.inflate(R.layout.type_product, parent,false));
            case ViewType.RECIPE_TYPE:
                return new RecipeHolder(mInflator.inflate(R.layout.type_recipe, parent,false));
        }
        return null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        holder.bind(mList.get(position));
    }


    @Override
    public int getItemViewType(int position) {
        return mList.get(position).getViewType();
    }

    public int getItemCount() {
        return mList.size();
    }

    public static class CollectionHolder extends BaseViewHolder<Collection> {
        private TextView mItem;

        public CollectionHolder(View itemView) {
            super(itemView);
            mItem = (TextView) itemView.findViewById(R.id.item);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context c = v.getContext();
                    Toast.makeText(c, "Dddd", Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void bind(Collection object) {
            mItem.setText(object.getTitle());
        }
    }

    public static class RecipeHolder extends BaseViewHolder<Recipe> {
        private TextView mItem;
        private List<Recipe> recipeList = new ArrayList<>();

        public RecipeHolder(View itemView) {
            super(itemView);
            mItem = (TextView) itemView.findViewById(R.id.item);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context c = v.getContext();
                    int position = getAdapterPosition();
                    Recipe click = recipeList.get(position);
                    int id = click.getId();

                    if (id == 0) {
                        Toast.makeText(c, "Selected: " + click.getTitle(), Toast.LENGTH_LONG).show();
                    }
                    else if(id == 1) {
                        Toast.makeText(c, "Selected: " + click.getTitle(), Toast.LENGTH_LONG).show();
                    }
                }
            });
        }

        @Override
        public void bind(Recipe object) {
            mItem.setText(object.getTitle());
        }
    }


    public static class ProductHolder extends BaseViewHolder<Product> {
        private TextView mItem;
        private List<Product> storyList = new ArrayList<>();

        public ProductHolder(View itemView) {
            super(itemView);
            mItem = (TextView) itemView.findViewById(R.id.item);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context c = v.getContext();
                    int position = getAdapterPosition();
                    Product click = storyList.get(position);
                    int id = click.getId();

                    if (id == 0) {
                        Toast.makeText(c, "Selected: " + click.getTitle(), Toast.LENGTH_LONG).show();
                    }
                    else if(id == 1) {
                        Toast.makeText(c, "Selected: " + click.getTitle(), Toast.LENGTH_LONG).show();
                    }
                }
            });
        }

        @Override
        public void bind(Product object) {
            mItem.setText(object.getTitle());
        }
    }


}

Logcat

2019-07-29 14:12:07.329 17223-17223/com.pollux.recyclerviewbinding E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.pollux.recyclerviewbinding, PID: 17223
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.get(ArrayList.java:437)
        at com.pollux.recyclerviewbinding.InventoryAdapter$ProductHolder$1.onClick(InventoryAdapter.java:122)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25885)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
    ```

首先:您應該在OnBindViewHolder方法中處理onClick

第二:最好使用這樣的接口:

public interface OnRecyclerItemClick{
   void onRecyclerItemClick(int position)
}

並在OnBindViewHolder中像這樣使用它:

 @Override
    @SuppressWarnings("unchecked")
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        holder.bind(mList.get(position));
        listener.onRecyclerItemClick(position);
    }

哪個listenerOnRecyclerItemClick ,您可以在構造函數或setter方法中對其進行初始化:

public void setOnRecyclerItemClick(OnRecyclerItemClick listener){
this.listener = listener;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM