How to pass values from RecycleAdapter to MainActivity or Other Activities

前端 未结 6 1173
小蘑菇
小蘑菇 2020-12-12 16:04

I am working on a shopping cart app,Items are displayed as below.There is a plus, minus (+/-) buttons to choose the number of quantity.

If product quantity is chang

6条回答
  •  攒了一身酷
    2020-12-12 16:15

    I failed to do it with both Interface and Observer pattern. But Local Broadcast worked for me.

    In Adapter

    String ItemName = tv.getText().toString();
                    String qty = quantity.getText().toString();
                    Intent intent = new Intent("custom-message");
                    //            intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
                    intent.putExtra("quantity",qty);
                    intent.putExtra("item",ItemName);
                    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    

    Main Activity

    public void onCreate(Bundle savedInstanceState) {
    
      ...
    
      // Register to receive messages.
      // We are registering an observer (mMessageReceiver) to receive Intents
      // with actions named "custom-message".
      LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
          new IntentFilter("custom-message"));
    }
    
    ...
    public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // Get extra data included in the Intent
                String ItemName = intent.getStringExtra("item");
                String qty = intent.getStringExtra("quantity");
                 Toast.makeText(MainActivity.this,ItemName +" "+qty ,Toast.LENGTH_SHORT).show();
            }
        };
    

提交回复
热议问题