我有一个 ID 为 widgetCount 的 editText,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newRoomLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/widgetName"
android:gravity="center"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:fontFamily="@font/montserrat_bold"
android:textSize="25sp"
android:text="@string/app_name" />
<EditText
android:id="@+id/widgetCount"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_gravity="end"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:gravity="center"
android:autofillHints="name"
android:text="@string/count_default"
android:hint="@string/count_hint"
android:inputType="number" />
</LinearLayout>
这是插入到回收器视图中的块。问题本身:如何从 edittext 获取文本?
回调不适合我。我尝试了一下,因为每个人都说英语。堆栈溢出版本:
for (int i = 0; i < newRoomRecycler.getAdapter().getItemCount();i++) {
View view = newRoomRecycler.getChildAt(i);
EditText widgetCount = view.findViewById(R.id.widgetCount);
}
但是,第 2 行有错误:
attempt to invoke virtual method 'android.view.View android.view.View.findViewByid(int)' on a null object reference
适配器:
public class NewRoomAdapter extends RecyclerView.Adapter<NewRoomAdapter.NewRoomViewHolder> {
private final Context context;
private final List<NewRoom> newRooms;
public NewRoomAdapter(Context context, List<NewRoom> newRooms) {
this.context = context;
this.newRooms = newRooms;
}
@NonNull
@Override
public NewRoomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View newRoomItems = LayoutInflater.from(context).inflate(R.layout.new_room_block, parent, false);
return new NewRoomViewHolder(newRoomItems);
}
@Override
public void onBindViewHolder(@NonNull NewRoomViewHolder holder, @SuppressLint("RecyclerView") int position) {
holder.newRoomText.setText(newRooms.get(position).getText());
}
@Override
public int getItemCount() {
return newRooms.size();
}
public static final class NewRoomViewHolder extends RecyclerView.ViewHolder {
private final TextView newRoomText;
public NewRoomViewHolder(@NonNull View itemView) {
super(itemView);
newRoomText = itemView.findViewById(R.id.widgetName);
}
}
}
这是适配器传递到回收器视图的方式:
private void setNewRoomRecycler(List<NewRoom> newRoomList) {
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
newRoomRecycler = findViewById(R.id.newRoomRecycler);
newRoomRecycler.setLayoutManager(layoutManager);
newRoomAdapter = new NewRoomAdapter(this, newRoomList);
newRoomRecycler.setAdapter(newRoomAdapter);
}
我读到了有关该错误的信息,在解决方案中他们说该对象根本不存在。
请帮帮我!
我使用了回调并将其保存到哈希表中:
添加了 HashMap 初始化:
和
还添加了一个函数来检查文本是否已更改:
和