RecyclerView中的开关按钮有问题

时间:2018-08-25 13:34:18

标签: android firebase-realtime-database android-recyclerview

我是Android Studio和Firebase编程的新手。 我正在尝试用RecyclerView编写一个简单的shoplist-app,其中每个项目都包含一个TextView和一个Switch-button。

如果我在RecyclerView中添加了七个以上的项目,则开关按钮开始表现得很奇怪,并检查了其他几个开关按钮。我知道RecyclerView中每个列表项的回收,并且已经尝试用Google搜索这个“问题”,但是还没有找到在我的代码中实现其他人答案的方法。我想我已经以某种方式弄糟了Adapter或ViewHolder。

这是我的适配器:

public class ListAdapter extends RecyclerView.Adapter<ShoppingItemViewHolder> {

private ArrayList<ShoppingItem> mShoppingItems = new ArrayList<>();

@NonNull
@Override
public ShoppingItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    Context mContext = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View listItemView = inflater.inflate(R.layout.list_item, parent, false);
    Switch boughtSwitch = listItemView.findViewById(R.id.boughtSwitchId);
    TextView itemTextView = listItemView.findViewById(R.id.itemTextView);
    return new ShoppingItemViewHolder(listItemView);

}

@Override
public void onBindViewHolder(@NonNull ShoppingItemViewHolder holder, int position) {
    ShoppingItem shoppingItem = mShoppingItems.get(position);
    holder.bind(shoppingItem);
}

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

public void addItem(ShoppingItem shoppingItem){
    mShoppingItems.add(shoppingItem);
    notifyDataSetChanged();
}

public void removeItem(ShoppingItem shoppingItem){
    mShoppingItems.remove(shoppingItem);
    notifyDataSetChanged();
}

@Override
public long getItemId(int position) {
    return position;
}

这是我的“ ShoppingItem” ViewHolder(如果有问题,请使用单独的文件):

class ShoppingItemViewHolder extends RecyclerView.ViewHolder {
private final TextView productName;
private final Switch boughtSwitch;
public static final String ITEMS_FIREBASE_KEY = "ItemsList";
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(ITEMS_FIREBASE_KEY);


public ShoppingItemViewHolder(View view) {
super(view);
    productName = view.findViewById(R.id.itemTextView);
    boughtSwitch = view.findViewById(R.id.boughtSwitchId);
}

public void bind(final ShoppingItem shoppingItem){
    productName.setText(shoppingItem.productName);


    boughtSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                boughtSwitch.setText("Köpt!");
                shoppingItem.bought = true;
                ref.child(shoppingItem.pushKey).child("bought").setValue(true);
            } else {
                boughtSwitch.setText("Köpt?");
                shoppingItem.bought = false;
                ref.child(shoppingItem.pushKey).child("bought").setValue(false);
            }


        }
    });
    boughtSwitch.setChecked(shoppingItem.bought);
}

我的MainActivity:

public class MainActivity extends AppCompatActivity
implements ChildEventListener{
private ArrayList<ShoppingItem> shoppingItems = new ArrayList<>();
public static final String ITEMS_FIREBASE_KEY = "ItemsList";

FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = firebaseDatabase.getReference(ITEMS_FIREBASE_KEY);

private TextView itemText;
private RecyclerView itemList;
private ListAdapter itemAdapter;

private EditText itemEntry;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    itemList = findViewById(R.id.item_recycler_list);
    itemList.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL, false));

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    itemText = findViewById(R.id.itemTextView);


    itemEntry = findViewById(R.id.addItemEditText);

    FloatingActionButton fab =  findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                   // .setAction("Action", null).show();
            pushToFirebase();
        }
    });

    itemAdapter = new ListAdapter();
    itemList.setAdapter(itemAdapter);

    ref.addChildEventListener(this);

}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();


    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {

        removeItemsFromFirebase();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void pushToFirebase() {
    String item = itemEntry.getText().toString();
    boolean bought = false;
    ShoppingItem shoppingItem = new ShoppingItem(item, bought);
    shoppingItem.pushKey = ref.push().getKey();
    ref.child(shoppingItem.pushKey).setValue(shoppingItem);
}

private void removeItemsFromFirebase() {

    DatabaseReference queryRef = FirebaseDatabase.getInstance().getReference(ITEMS_FIREBASE_KEY);

    Query boughtQuery = queryRef.child(ITEMS_FIREBASE_KEY).orderByChild("bought").equalTo(true);

    boughtQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot querySnap : dataSnapshot.getChildren()){
                querySnap.getRef().removeValue();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}



@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    ShoppingItem recievedShoppingItem = dataSnapshot.getValue(ShoppingItem.class);
    itemAdapter.addItem(recievedShoppingItem);
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
    itemAdapter.clearItemList();
    ShoppingItem recievedShoppingItem = dataSnapshot.getValue(ShoppingItem.class);
    itemAdapter.addItem(recievedShoppingItem);
}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
    ShoppingItem recievedShoppingItem = dataSnapshot.getValue(ShoppingItem.class);
    itemAdapter.removeItem(recievedShoppingItem);
    itemAdapter.notifyDataSetChanged();
}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
    itemAdapter.notifyDataSetChanged();
}

@Override
public void onCancelled(DatabaseError databaseError) {

}

编辑:

这是我的“ list_item.xml”:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/itemTextView"
    android:layout_width="218dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="TextView"
    android:textSize="20dp" />

<Switch
    android:id="@+id/boughtSwitchId"
    android:layout_width="113dp"
    android:layout_height="49dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/bought_switch_text" />

我知道要经历很多事情,但是如果有人想帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

我设法使用Firebase UI数据库使其工作。 这样一来,我就不必为适应《 Childlisteners》的作者编写自己的方法。 如果有人愿意,可以发布代码!