gpt4 book ai didi

java - RecyclerView 中的项目数组

转载 作者:行者123 更新时间:2023-12-02 02:22:24 25 4
gpt4 key购买 nike

我有一个类将 recyclerView 呈现为列表(由数组中的元素数量定义),但在合并数据类时遇到问题。

public class Tab3 extends Fragment {
RecyclerView recyclerView;
String[] Items={"Item 0", "Item 1", "Item 2",};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3, container, false);

recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(new Adapter(this.getActivity(), Items));

return rootView;
}
}

下面是应包含数据/适配器的类:

public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
String[] items ={"Item 0", "Item 1", "Item 2",};

public Adapter(Context context, String[] items) {
this.context = context;
this.items = this.items;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(R.layout.custom_row, parent, false);
Item item = new Item(row);
return item;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
((Item) holder).textView.setText(items[position]);
((Item) holder).toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Clicked at position " + position, Toast.LENGTH_SHORT).show();
}
});
}

@Override
public int getItemCount() {
return items.length;
}

public class Item extends RecyclerView.ViewHolder {
TextView textView;
ToggleButton toggleButton;

public Item(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.item);
toggleButton = (ToggleButton) itemView.findViewById(R.id.toggleButton);
}
}
}

如果我删除该行

String[] items ={"Item 0", "Item 1", "Item 2",};

在后一个类中,getItemCount() 返回一个 null (items.length) - 但是,我不知道如何将其传递给另一段代码。

最佳答案

而不是适配器中的这个

String[] items ={"Item 0", "Item 1", "Item 2",};

String[] items;

还有这个

this.items = this.items;

public Adapter(Context context, String[] items) {
this.context = context;
this.items = items;
}

您可以检查您的getItemCount,但我认为没有必要进行此检查。

@Override
public int getItemCount() {
if (items != null) {
return items.length;
}
return 0;
}

关于java - RecyclerView 中的项目数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48316506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com