Получить данные из RecyclerView - PullRequest
0 голосов
/ 05 ноября 2018

Я использую RecyclerView в приложении, используя пользовательский адаптер. Я хочу разобраться с существующим меню RecyclerView пунктов. Для доступа к ним, как к обычным переменным, чтобы я мог применить определенное условие или отправить их в текстовом сообщении и т. Д. За пределами моего адаптера класса.

Как получить доступ к RecyclerView элементам?

Матрица кодовых классов:

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);

        addItem();

        Button button = findViewById(R.id.get_item);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                    I want when I press the button
                    The items are called
                 */
            }
        });

    }

    public void addItem() {

        List<Shops> shops = new ArrayList<>();
        String[] cloth = {"Silk", "Cotton", "Linen"};
        String[] wood = {"Sandal", "Jawi", "Pine"};
        String[] metal = {"Window", "door", "roof"};

        RecyclerView recyclerView = findViewById(R.id.list_shop);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        for (int i = 0; i < cloth.length; i++) {

            Shops shopsList = new Shops(cloth[i], wood[i], metal[i]);

            shops.add(shopsList);
        }

        ShopsAdapter adapter = new ShopsAdapter(shops);
        recyclerView.setAdapter(adapter);
    }
}

код списка классов

public class Shops {
    String cloth, wood, metal;

    public Shops(String cloth, String wood, String metal) {
        this.cloth = cloth;
        this.wood = wood;
        this.metal = metal;
    }
}

Адаптер класса кода

public class ShopsAdapter extends RecyclerView.Adapter<ShopsAdapter.ShopsHolder> {

    private List<Shops> shopsList;

    public ShopsAdapter(List<Shops> shops) {
        this.shopsList = shops;
    }

    @Override
    public ShopsHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View row = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.template_recycler_view, viewGroup, false);
        ShopsHolder holder = new ShopsHolder(row);
        return holder;
    }

    @Override
    public void onBindViewHolder(ShopsHolder holder, int i) {

        Shops shops = shopsList.get(i);
        holder.cloth.setText(shops.cloth);
        holder.wood.setText(shops.wood);
        holder.metal.setText(shops.metal);

    }

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

    class ShopsHolder extends RecyclerView.ViewHolder {
        private TextView cloth, wood, metal;

        public ShopsHolder(View itemView) {
            super(itemView);
            cloth = itemView.findViewById(R.id.cloth);
            wood = itemView.findViewById(R.id.wood);
            metal = itemView.findViewById(R.id.metal);
        }
    }
}

Если вам нужен код XML, я добавлю его в другой ответ.

Ответы [ 3 ]

0 голосов
/ 05 ноября 2018

Создайте свой класс модели / POJO с помощью getters () и setters () следующим образом

public class Shops {

    private String cloth;
    private String wood;
    private String metal;

    public Shops(String cloth, String wood, String metal) {
        this.cloth = cloth;
        this.wood = wood;
        this.metal = metal;
    }

    public String getCloth() {
        return cloth;
    }

    public void setCloth(String cloth) {
        this.cloth = cloth;
    }

    public String getWood() {
        return wood;
    }

    public void setWood(String wood) {
        this.wood = wood;
    }

    public String getMetal() {
        return metal;
    }

    public void setMetal(String metal) {
        this.metal = metal;
    }
}

Теперь объявите ArrayList глобально и добавьте в него элементы. Когда вы нажимаете кнопку просто получить доступ к ним с индексом. Для этого вы можете запустить цикл for.

public class MainActivity extends AppCompatActivity {

private  List<Shops> shops;

protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);
    super.onCreate(savedInstanceState);
    shops= new ArrayList<>();
    addItem();

    Button button = findViewById(R.id.get_item);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*
                I want when I press the button
                The items are called
             */
            shops.get(1).getCloth();
            shops.get(1).getWood();
            shops.get(1).getMetal();

            // do whatever you want with them

        }
    });

}

public void addItem() {


    String[] cloth = {"Silk", "Cotton", "Linen"};
    String[] wood = {"Sandal", "Jawi", "Pine"};
    String[] metal = {"Window", "door", "roof"};

    RecyclerView recyclerView = findViewById(R.id.list_shop);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    for (int i = 0; i < cloth.length; i++) {

        Shops shopsList = new Shops(cloth[i], wood[i], metal[i]);

        shops.add(shopsList);
    }
0 голосов
/ 05 ноября 2018

Ваш код выглядит как то, что вам нужно, но я не думаю, что это действительно хороший способ. Вместо того, чтобы создавать публичный список в каком-то месте вашего проекта для кэширования нужных вам данных, лучше сделать этот список приватным в вашем адаптере и получать нужные данные через адаптер, добавив getItem (int pos), который возвращает элемент по параметру «pos» вы переходите к нему, это безопаснее и профессиональнее. Есть много способов решить проблему, но какой из них лучший ...

0 голосов
/ 05 ноября 2018

спасибо. После повторных экспериментов. Я смог достичь результата. Это использует для цикла Внутри вы добавляете элемент Так

  public void addItem() {

        String[] cloth = {"Silk", "Cotton", "Linen"};
        String[] wood = {"Sandal", "Jawi", "Pine"};
        String[] metal = {"Window", "door", "roof"};

        RecyclerView recyclerView = findViewById(R.id.list_shop);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        for (int i = 0; i < cloth.length; i++) {

            Shops shopsList = new Shops(cloth[i], wood[i], metal[i]);

            shops.add(shopsList);

        }

        ShopsAdapter adapter = new ShopsAdapter(shops);
        recyclerView.setAdapter(adapter);

    // From here begins the solution code
        for (int i = 0; i < cloth.length; i++) {

            String clothMy = shops.get(i).cloth;
            String woodMy = shops.get(i).wood;
            String metalMy = shops.get(i).metal;

            Log.i("TAG",clothMy);
            Log.i("TAG",woodMy);
            Log.i("TAG",metalMy);

        }
    // Here ends the solution code

    }
...