android 在Java中,我们不能将int值传递给回收器视图吗?

3zwjbxry  于 2022-12-09  发布在  Android
关注(0)|答案(2)|浏览(98)

我创建了一个类来显示临时数据。显然我的应用程序崩溃了,但如果我把int sno改为String sno,那么就没有问题了。我想知道int,如果是,那么怎么做?

public class Contact
{
    public int sno;
    public String phone;
    public String name;

    Contact(int sno, String phone, String name)
    {
        this.sno = sno;
        this.phone = phone;
        this.name = name;
    }
}

我的自定义适配器类文件--〉

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>
{
    private final Contact[] localDataSet;
//    private TextView textView;
    private TextView textView2;
    private TextView textView3;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView2;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView2 = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView2;
        }
    }

    /**
     * step 1 Initialize the dataset of the Adapter.
     *
     */
    public CustomAdapter(Contact[] dataSet) {
        localDataSet = dataSet;
    }

    // Create new views (invoked by the layout manager)
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.contact_layout, viewGroup, false);
//        textView = view.findViewById(R.id.textView);
        textView2 = view.findViewById(R.id.textView2);
        textView3 = view.findViewById(R.id.textView3);
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position)
    {
        // Get element from your dataset at this position and replace the
        // contents of the view with that element
//        textView.setText(localDataSet[position].sno);
        textView2.setText(localDataSet[position].name);
        textView3.setText(localDataSet[position].phone);
    }

我注解了一个文本视图暂时不得到sno打印,然后我的应用程序的工作

ryevplcw

ryevplcw1#

如果您使用int作为TextView::setText的参数,那么您需要传递一个资源id。如果您看到错误日志,您的崩溃可能会显示类似于“could not resolve resource id for [some_number]"的内容。
int转换为String,然后再将其设置为您的TextView,这样就不会再出现问题,即textView.setText(String.valueOf(localDataSet[position].sno));

ut6juiuv

ut6juiuv2#

当你将int值设置为textView时,应用崩溃了。你可以这样使用它。

textView.setText(localDataSet[position].sno+"")

相关问题