Обновите RecyclerView новыми данными в MasterDetail Flow - PullRequest
0 голосов
/ 19 мая 2019

Я делаю мобильное приложение для планшетов и добавил мастер / подробный поток, используя шаги Android Studio.У меня есть группа из 4 кнопок над главной деталью, чтобы выбрать «Продукт», а затем, когда вы нажимаете одну из них, RecyclerView обновляется данными.

Моя проблема заключается в том, что если вы нажимаете одну кнопку (продукт), затем другой, и другой, и т.д .. Все данные загружаются вместе, поэтому мне нужно выяснить, как обновить / обновить RecyclerView.

enter image description here

В моем RecyclerViewAdapter я добавил метод для очистки, обновления ITEMS и затем notifyDataSetChanged.Это работает хорошо для остальных кнопок, но не для первой кнопки, которая по умолчанию нажимается программно.Первая кнопка снова настроила RecyclerView.

enter image description here

ProductListActivity

public class ProductListActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;

    // Group of buttons
    private Button[] btn = new Button[4];
    private Button btn_unfocus;
    private int[] btn_id = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3};

    private View recyclerView;
    private ItemRecyclerViewAdapter mAdapter;
    private MyDatabase mMyDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);

        if (findViewById(R.id.product_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-w900dp).
            // If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;
        }

        mMyDatabase = Utils.getDatabase(ProductListActivity.this);

        recyclerView = findViewById(R.id.product_list);
        assert recyclerView != null;

        // Initialize the button group
        initButtonGroup();
    }

    private void initButtonGroup() {
        for(int i = 0; i < btn.length; i++){
            btn[i] = (Button) findViewById(btn_id[i]);
            btn[i].setBackgroundColor(ContextCompat.getColor(this, R.color.customGreenDark));
            btn[i].setTextColor(Color.WHITE);
            btn[i].setOnClickListener(this);
        }

        btn_unfocus = btn[0];

        // Set the first button clicked by default
        btn[0].performClick();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn0 :
                setFocus(btn_unfocus, btn[0]);
                List<Presentation.IdAndPresentationTuple> presentationList1 = mMyDatabase.presentationDao()
                        .getProductRepresentationsByName("Product 1");
                // Set up for the first time
                setupRecyclerView((RecyclerView) recyclerView, presentationList1);
                mAdapter.updateData(presentationList1);
                break;

            case R.id.btn1:
                setFocus(btn_unfocus, btn[1]);
                List<Presentation.IdAndPresentationTuple> presentationList2 = mMyDatabase.presentationDao()
                        .getProductRepresentationsByName("Product 2");
                // Update data
                mAdapter.updateData(presentationList2);
                break;

            case R.id.btn2:
                setFocus(btn_unfocus, btn[2]);
                List<Presentation.IdAndPresentationTuple> presentationList3 = mMyDatabase.presentationDao()
                        .getProductRepresentationsByName("Product 3");
                // Update data
                mAdapter.updateData(presentationList3);
                break;
        }
    }

    private void setFocus(Button btn_unfocus, Button btn_focus){
        btn_unfocus.setTextColor(Color.WHITE);
        btn_unfocus.setTypeface(null, Typeface.NORMAL);
        btn_unfocus.setBackgroundColor(ContextCompat.getColor(this, R.color.customGreenDark));
        btn_focus.setTextColor(Color.BLACK);
        btn_focus.setTypeface(null, Typeface.BOLD);
        btn_focus.setBackground(getDrawable(R.drawable.button_border_yellow));
        this.btn_unfocus = btn_focus;
    }

    private void setupRecyclerView(@NonNull RecyclerView recyclerView, List<Presentation.IdAndPresentationTuple> ITEMS) {
        mAdapter = new ItemRecyclerViewAdapter(this, ITEMS, mTwoPane);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(mAdapter);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }
}

ItemRecyclerViewAdapter

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

    private final ProductListActivity mParentActivity;
    private final List<Presentation.IdAndPresentationTuple> mValues;
    private final boolean mTwoPane;

    ItemRecyclerViewAdapter(ProductListActivity parent,
                            List<Presentation.IdAndPresentationTuple> items,
                            boolean twoPane) {
        mParentActivity = parent;
        mValues = items;
        mTwoPane = twoPane;
    }

    // My custom method to clear, update and notifyDataSetChanged
    public void updateData(List<Presentation.IdAndPresentationTuple> items) {
        mValues.clear();
        mValues.addAll(items);
        notifyDataSetChanged();
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Presentation.IdAndPresentationTuple item = (Presentation.IdAndPresentationTuple) view.getTag();
            if (mTwoPane) {
                Bundle arguments = new Bundle();
                // Send the id of the product to show
                arguments.putString(ProductDetailFragment.ARG_ITEM_ID, String.valueOf(item.getId()));
                ProductDetailFragment fragment = new ProductDetailFragment();
                fragment.setArguments(arguments);
                mParentActivity.getSupportFragmentManager().beginTransaction()
                        .replace(R.id.product_detail_container, fragment)
                        .commit();
            } else {
                Context context = view.getContext();
                Intent intent = new Intent(context, ProductDetailActivity.class);
                intent.putExtra(ProductDetailFragment.ARG_ITEM_ID, String.valueOf(item.getId()));

                context.startActivity(intent);
            }
        }
    };

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

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        holder.mIdView.setText(String.valueOf(mValues.get(position).getId()));
        holder.mRepresentationNameView.setText(mValues.get(position).getPresentationName());

        holder.itemView.setTag(mValues.get(position));
        holder.itemView.setOnClickListener(mOnClickListener);
    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        final TextView mIdView;
        final TextView mRepresentationNameView;

        ViewHolder(View view) {
            super(view);
            mIdView = (TextView) view.findViewById(R.id.id);
            mRepresentationNameView = (TextView) view.findViewById(R.id.representationName);
        }
    }

}

Моя цель - правильно обновлять / обновлять RecyclerView при каждом нажатии новой кнопки (Продукт).

1 Ответ

1 голос
/ 19 мая 2019

Все выглядит хорошо. Просто внесите следующие изменения:

  1. Вы уже устанавливаете RecyclelerView с нулевыми данными в:

    setupRecyclerView ((RecyclerView) recyclerView, null);

Итак, вам не нужно устанавливать его снова в первой кнопке.

  1. В вашем адаптере добавьте следующее изменение в метод getItemCount ()

    @ Override public int getItemCount () { если (mValues ​​== NULL) возврат 0;

    return mValues.size (); }

С помощью этого кода вы сообщаете адаптеру, что в начале, когда mValues ​​будет нулевым, данные отображаться не будут. Поэтому количество предметов установлено на 0.

Обновление

  1. Не программно нажимайте первую кнопку только для отображения некоторых данных при открытии приложения. Хотя все в порядке, это не очень хорошая практика кодирования.

Внутри onCreate () вызовите функцию setupRecyclerView (), чтобы отобразить данные первой кнопки.

Вот изменение:

ProductListActivity

public class ProductListActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;

    // Group of buttons
    private Button[] btn = new Button[4];
    private Button btn_unfocus;
    private int[] btn_id = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3};

    private View recyclerView;
    private ItemRecyclerViewAdapter mAdapter;
    private MyDatabase mMyDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);

        if (findViewById(R.id.product_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-w900dp).
            // If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;
        }

        mMyDatabase = Utils.getDatabase(ProductListActivity.this);

        recyclerView = findViewById(R.id.product_list);

       //Get the data that you want to display for the first time
        List<Presentation.IdAndPresentationTuple> presentationList1 = mMyDatabase.presentationDao()
                        .getProductRepresentationsByName("Product 1");


                // Set up recycler view for the first time

               setupRecyclerView((RecyclerView) recyclerView, presentationList1);

                mAdapter.updateData(presentationList1); //Call the update method

        // Initialize the button group
        initButtonGroup();
    }

    private void initButtonGroup() {
        for(int i = 0; i < btn.length; i++){
            btn[i] = (Button) findViewById(btn_id[i]);
            btn[i].setBackgroundColor(ContextCompat.getColor(this, R.color.customGreenDark));
            btn[i].setTextColor(Color.WHITE);
            btn[i].setOnClickListener(this);
        }

        btn_unfocus = btn[0];

        // Set the first button clicked by default
        //btn[0].performClick(); //Don't perform manual click
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn0 :
                setFocus(btn_unfocus, btn[0]);
                List<Presentation.IdAndPresentationTuple> presentationList1 = mMyDatabase.presentationDao()
                        .getProductRepresentationsByName("Product 1");

                mAdapter.updateData(presentationList1);
                break;

            case R.id.btn1:
                setFocus(btn_unfocus, btn[1]);
                List<Presentation.IdAndPresentationTuple> presentationList2 = mMyDatabase.presentationDao()
                        .getProductRepresentationsByName("Product 2");
                // Update data
                mAdapter.updateData(presentationList2);
                break;

            case R.id.btn2:
                setFocus(btn_unfocus, btn[2]);
                List<Presentation.IdAndPresentationTuple> presentationList3 = mMyDatabase.presentationDao()
                        .getProductRepresentationsByName("Product 3");
                // Update data
                mAdapter.updateData(presentationList3);
                break;
        }
    }

    private void setFocus(Button btn_unfocus, Button btn_focus){
        btn_unfocus.setTextColor(Color.WHITE);
        btn_unfocus.setTypeface(null, Typeface.NORMAL);
        btn_unfocus.setBackgroundColor(ContextCompat.getColor(this, R.color.customGreenDark));
        btn_focus.setTextColor(Color.BLACK);
        btn_focus.setTypeface(null, Typeface.BOLD);
        btn_focus.setBackground(getDrawable(R.drawable.button_border_yellow));
        this.btn_unfocus = btn_focus;
    }

    private void setupRecyclerView(@NonNull RecyclerView recyclerView, List<Presentation.IdAndPresentationTuple> ITEMS) 
    {


        if(recyclerView.getAdapter()==null)
        {
            //Set the Adapter for the first time only 
             mAdapter = new ItemRecyclerViewAdapter(this, null, mTwoPane);
              recyclerView.setHasFixedSize(true);
              recyclerView.setAdapter(mAdapter);
              recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        }

    }
}

ItemRecyclerViewAdapter

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

    private final ProductListActivity mParentActivity;
    private final List<Presentation.IdAndPresentationTuple> mValues;
    private final boolean mTwoPane;

    ItemRecyclerViewAdapter(ProductListActivity parent,
                            List<Presentation.IdAndPresentationTuple> items,
                            boolean twoPane) {
        mParentActivity = parent;
        mValues = items;
        mTwoPane = twoPane;
    }

    // My custom method to clear, update and notifyDataSetChanged
    public void updateData(List<Presentation.IdAndPresentationTuple> items) 
    {
        if(items!=null)
        {
             mValues.clear();
            mValues.addAll(items);
            notifyDataSetChanged();
        }

    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Presentation.IdAndPresentationTuple item = (Presentation.IdAndPresentationTuple) view.getTag();
            if (mTwoPane) {
                Bundle arguments = new Bundle();
                // Send the id of the product to show
                arguments.putString(ProductDetailFragment.ARG_ITEM_ID, String.valueOf(item.getId()));
                ProductDetailFragment fragment = new ProductDetailFragment();
                fragment.setArguments(arguments);
                mParentActivity.getSupportFragmentManager().beginTransaction()
                        .replace(R.id.product_detail_container, fragment)
                        .commit();
            } else {
                Context context = view.getContext();
                Intent intent = new Intent(context, ProductDetailActivity.class);
                intent.putExtra(ProductDetailFragment.ARG_ITEM_ID, String.valueOf(item.getId()));

                context.startActivity(intent);
            }
        }
    };

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

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        holder.mIdView.setText(String.valueOf(mValues.get(position).getId()));
        holder.mRepresentationNameView.setText(mValues.get(position).getPresentationName());

        holder.itemView.setTag(mValues.get(position));
        holder.itemView.setOnClickListener(mOnClickListener);
    }

    @Override
    public int getItemCount() 
    {
        if(mValues==null)
        {
            return 0;
        }
        return mValues.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        final TextView mIdView;
        final TextView mRepresentationNameView;

        ViewHolder(View view) {
            super(view);
            mIdView = (TextView) view.findViewById(R.id.id);
            mRepresentationNameView = (TextView) view.findViewById(R.id.representationName);
        }
    }

}
...