Как получить доступ к индикатору прогресса элемента в RecyclerVIew из MainActivity - PullRequest
1 голос
/ 03 апреля 2020

У меня есть 10 предметов внутри RecyclerView. Каждый элемент имеет ProgressBar. Как я могу получить доступ к ProgressBar из MainActivity. Это мой класс адаптера. Я обрабатываю события, используя интерфейс, когда я нажимаю кнопку элемента, чтобы изменить индикатор выполнения.

public class MyHospitalAdapter extends RecyclerView.Adapter<MyHospitalAdapter.MyViewHolder> {
private List<Hospital> mHospitalList;
private Context context;

public onImageClickListener mCallBack;


public interface onImageClickListener {
    void clickOnImage(int id);

    void onTextViewOfPriceSelected(int id, int amountOfProduction, int price, int time, int multiplier);
}

// 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 static class MyViewHolder extends RecyclerView.ViewHolder {
    // each data item is just a string in this case


    ImageView imageView;
    ProgressBar progressBar;
    TextView textViewOnProgressBar;
    Button price;
    TextView productionAmount;
    TextView nameHospital;


    public MyViewHolder(@NonNull View itemView, ImageView imageView, ProgressBar progressBar, TextView textViewOnProgressBar, Button price, TextView productionAmount, TextView nameHospital) {
        super(itemView);
        this.imageView = imageView;
        this.progressBar = progressBar;
        this.textViewOnProgressBar = textViewOnProgressBar;
        this.price = price;
        this.productionAmount = productionAmount;
        this.nameHospital = nameHospital;
    }


}

// Provide a suitable constructor (depends on the kind of dataset)
public MyHospitalAdapter(List<Hospital> mHospitalsList, Context context) {
    this.mHospitalList = mHospitalsList;
    this.context = context;
}

// Create new views (invoked by the layout manager)
@Override
public MyHospitalAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                         int viewType) {

    OneBusinesBinding binding =
            DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),
                    R.layout.one_busines, parent, false);

    MyViewHolder vh = new MyViewHolder(binding.constraintLayout, binding.imageBusiness, binding.progressBar, binding.textViewOnProgressbar, binding.price, binding.amountofProduction, binding.nameHospital);
    return vh;
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    Hospital currentItem = mHospitalList.get(position);
    int price = currentItem.getPrice();
    int productionAmount = currentItem.getAmount();
    int time = currentItem.getAmount();
    int mMultiplier = currentItem.getMultiplier();


    holder.imageView.setImageResource(AndroidImageAssets.getPictures().get(position));
    holder.productionAmount.setText(context.getString(R.string.amount_of_production, productionAmount));

    holder.price.setText(context.getString(AssetsUpgradeStrings.getStrings_On_Button_Buy().get(position), convertNumberToString(price)));
    holder.progressBar.setProgressTintList(ColorStateList.valueOf(Color.GRAY));
    holder.nameHospital.setText(AssetsUpgradeStrings.getHospitalsNames().get(position));
    holder.textViewOnProgressBar.setText(context.getString(R.string.string_on_progressbar, position));


    holder.imageView.setOnClickListener((v) -> {

        mCallBack.clickOnImage(position);
    });

Это часть MainActivity, где я инициализирую свой адаптер.

recyclerView = binding.recyclerView;
    recyclerView.setHasFixedSize(true);


    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    binding.recyclerView.setHasFixedSize(true);
    mAdapter = new MyHospitalAdapter(mListHospitals,getApplicationContext());
    recyclerView.setAdapter(mAdapter);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(mAdapter);

Я передаю Список данных пункта.

1 Ответ

1 голос
/ 03 апреля 2020

Вы можете передать свой индикатор выполнения в методе интерфейса:

public interface onImageClickListener {
    void clickOnImage(int id, ProgressBar myProgressBar);

    void onTextViewOfPriceSelected(int id, int amountOfProduction, int price, int time, int multiplier);
}

И использовать его в обратном вызове в действии:

holder.imageView.setOnClickListener((v) -> {
        mCallBack.clickOnImage(position, holder.progressBar);
    });

ИЛИ

Вы можете передать свой экземпляр активности в конструкторе адаптера.

...
private MainActivity context;
...
public MyHospitalAdapter(List<Hospital> mHospitalsList, MainActivity context) {
    this.mHospitalList = mHospitalsList;
    this.context = context;
}

Запустить метод действия по нажатию кнопки и передать индикатор выполнения в качестве параметра метода:

 holder.imageView.setOnClickListener((v) -> {
        context.yourMethodHere(holder.progressBar)
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...