Android - 如何将文本视图值从 Activity-A 传递到适配器

Android - How do you pass textview values from Activity-A to an adapter

我正在开发购物车应用程序,需要一些有关适配器的帮助。我试图解决一个类似的问题 here 但它与我的情况有点不同。我有 3 个 classes:MakeSale.javaDetailsActivity.javaShoppingCartListAdapter.java。所以,这是流程。

MakeSale.java 中,我声明了两个数组列表,第一个是 cartItemArrayList 商店的顾客要购买的商品。这些是生产商名称、产品名称、数量、单位成本和第二个,cartCostItemsList 包含购物车中商品的总成本。

里面MakeSale.java

public static List<CartItem> cartItemArrayList = new ArrayList<>();
public static List<Double> cartCostItemsList = new ArrayList<>();

然后我有一个扩展 ArrayAdapter 的适配器 class。此 class 链接到显示在列表视图上的 XML、list_item。现在,这个 list_item 只显示生产商名称、产品名称、总数量、添加到购物车的每件商品的总成本。当用户想要对列表视图中的项目进行更改(增加或减少要购买的项目数量)时,list_item 已变为可点击。

里面ShoppingCartListAdapter.java

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.zynle.fisp_dealer.Dashboard;
import com.zynle.fisp_dealer.DetailsActivity;
import com.zynle.fisp_dealer.MakeSale;
import com.zynle.fisp_dealer.R;

import java.util.List;
import entities.CartItem;


public class ShoppingCartListAdapter extends ArrayAdapter<CartItem> {

private Context context;
private List<CartItem> cartItems;

public ShoppingCartListAdapter(Context context, List<CartItem> cartItems) {
    super(context, R.layout.list_item, cartItems);
    this.context = context;
    this.cartItems = cartItems;

}

public int getCount() {
    return cartItems.size();
}

public CartItem getItem(int position) {
    return cartItems.get(position);
}

public long getItemId(int position) {
    return cartItems.get(position).getId();
}


@NonNull
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater layoutInflater = (LayoutInflater) context.
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final CartItem currentProduct = getItem(position);

    View view = layoutInflater.inflate(R.layout.list_item, parent, false);

    TextView productName_txtv = (TextView) view.findViewById(R.id.nameTextView);
    TextView producerName_txtv = (TextView) view.findViewById(R.id.producerTextView);
    TextView productQuantity_txtv = (TextView) view.findViewById(R.id.qtyTextView);
    TextView productCost_txtv = (TextView) view.findViewById(R.id.priceTextView);

    productName_txtv.setText(cartItems.get(position).getProduct_txt());
    producerName_txtv.setText(cartItems.get(position).getProducer_txt());
    productQuantity_txtv.setText(String.valueOf(cartItems.get(position).getQuantity()));
    productCost_txtv.setText(String.valueOf(cartItems.get(position).getCost_txt()));

    productName_txtv.setText(currentProduct.getProduct_txt());

    int perItem = currentProduct.getCost_txt();
    int quantitee = currentProduct.getQuantity();

    final int total = perItem * quantitee;

    productCost_txtv.setText("Total: K" + total);
    productQuantity_txtv.setText(currentProduct.getQuantity() + " Selected");

    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent detailsIntent = new Intent(context, DetailsActivity.class);
            detailsIntent.putExtra("name", currentProduct.getProduct_txt());
            detailsIntent.putExtra("quantity", currentProduct.getQuantity());
            detailsIntent.putExtra("total", total);
            context.startActivity(detailsIntent);
        }
    });

    return view;
}


public void makeNewSale() {
    if (getCount() == 0) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.Theme_AppCompat_Light_Dialog_Alert);
        builder.setTitle(R.string.app_name);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setMessage("Cart is Empty!")
                .setCancelable(false)
                .setPositiveButton("Add new items", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        Intent intent = new Intent(getContext(), MakeSale.class);
                        getContext().startActivity(intent);

                    }
                })
                .setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent intent = new Intent(getContext(), Dashboard.class);
                        getContext().startActivity(intent);
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

}

我的代码处理所有关于增加和减少按钮点击数量的逻辑在一个名为 DetailsActivity.java 的 class 中,从意图上看。当然 DetailsActivity.java 链接到一些 xml 文件。

里面DetailsActivity.java

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import database.FISP_SQLiteDB;
import entities.CartItem;
import entities.Products;

public class DetailsActivity extends AppCompatActivity {

ImageView imageView;
TextView nameTextView, priceTextView, qtyTextView, available;
Button increaseQtyButton, decreaseQtyButton, contactSupplierButton, deleteButton, confirmButton;

private List<CartItem> cartItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_details);

    // Get any data passed in from Fragment
    Intent detailsIntent = getIntent();
    final String name = detailsIntent.getStringExtra("name");

    imageView = (ImageView) findViewById(R.id.imageView);
    nameTextView = (TextView) findViewById(R.id.nameTextView);
    available = (TextView) findViewById(R.id.availableQTY);
    priceTextView = (TextView) findViewById(R.id.priceTextView);
    qtyTextView = (TextView) findViewById(R.id.qtyText);
    increaseQtyButton = (Button) findViewById(R.id.increaseQtyButton);
    decreaseQtyButton = (Button) findViewById(R.id.decreaseQtyButton);
    contactSupplierButton = (Button) findViewById(R.id.contactSupplierButton);
    deleteButton = (Button) findViewById(R.id.deleteProductButton);
    confirmButton = (Button) findViewById(R.id.confirm);

    nameTextView.setText(name);

    int quantityPicker = Integer.parseInt(MakeSale.quantityPicker_Npkr.getText().toString());
    qtyTextView.setText("" + quantityPicker);

    final FISP_SQLiteDB db = new FISP_SQLiteDB(DetailsActivity.this);
    final Products product = db.getProduct(name);

    if (product != null) {

        final double productPrice = (product.getPrice() * quantityPicker);
        final int subQuantity = (product.getQuantity() - quantityPicker);

        priceTextView.setText("K" + productPrice);
        available.setText("Available Quantity is " + subQuantity);

        final int[] counter = {quantityPicker};
        final int[] counter1 = {quantityPicker};
        final int[] minteger = {1};

        increaseQtyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                qtyTextView.setText(String.valueOf(counter[0]++));
                int reducingQty = (subQuantity - counter1[0]++);
                double totalingPrice = productPrice + (product.getPrice()* minteger[0]++);
                available.setText(String.valueOf("Available Quantity is " + reducingQty));
                priceTextView.setText("K" + totalingPrice);

                decreaseQtyButton.setEnabled(true);

                if(reducingQty==0){
                    increaseQtyButton.setEnabled(false);
                    decreaseQtyButton.setEnabled(true);

                }
            }
        });

        decreaseQtyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                qtyTextView.setText(String.valueOf(counter[0]--));
                int increasingQty = (subQuantity - counter1[0]--);
                double totalingPrice = productPrice - (product.getPrice()* minteger[0]--);
                available.setText(String.valueOf("Available Quantity is " + increasingQty));
                priceTextView.setText("K" + totalingPrice);

                increaseQtyButton.setEnabled(true);

                if (increasingQty==product.getQuantity()){
                    increaseQtyButton.setEnabled(true);
                    decreaseQtyButton.setEnabled(false);

                }
            }
        });

        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case DialogInterface.BUTTON_POSITIVE:

                                //db.deleteProduct(name);
                                finish();
                                break;

                            case DialogInterface.BUTTON_NEGATIVE:
                                break;
                        }
                    }
                };
                AlertDialog.Builder ab = new AlertDialog.Builder(DetailsActivity.this, R.style.MyDialogTheme);
                ab.setMessage("Delete " + name + " ?").setPositiveButton("DELETE", dialogClickListener)
                        .setNegativeButton("CANCEL", dialogClickListener).show();
            }
        });


        contactSupplierButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                // Creating alert Dialog with two Buttons
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(DetailsActivity.this, R.style.MyDialogTheme);
                // Setting Dialog Title
                alertDialog.setTitle("Do you want to call?");
                // Setting Dialog Message
                alertDialog.setMessage("" + product.getSupplierName());
                // Setting Icon to Dialog
                //alertDialog.setIcon(R.drawable.warning);
                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // Write your code here to execute after dialog
                                dialog.cancel();
                            }
                        });
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // Write your code here to execute after dialog
                                Intent callIntent = new Intent(Intent.ACTION_CALL);
                                //callIntent.setData(Uri.parse("" + product.getSupplierPhone().trim()));
                                callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                callIntent.setData(Uri.parse("tel:" + product.getSupplierPhone()));

                                if (ActivityCompat.checkSelfPermission(DetailsActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    return;
                                }
                                DetailsActivity.this.startActivity(callIntent);
                            }
                        });

                // Showing Alert Message
                alertDialog.show();
            }
        });

        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //CartItem cartItem = new CartItem(producer, product, quantity, unitCost);
                //cartItemArrayList.add(cartItem);

                Intent intent = new Intent(DetailsActivity.this, ShoppingCart.class);
                startActivity(intent);
            }
        });
    }
  }
}

现在,当用户单击 confirmChangesBtn 时,如何将这些新值(新数量、新 totalCost)set/replace 放入列表视图的 list_item 中?通过这样做更改数组列表中的产品详细信息(cartItemArrayListcartCostItemsList)。将文本视图值从 DetailsActivity.java 传递到适配器以供显示?我该怎么做?任何人?

当用户从详细信息页面更改购物车值并再次在适配器中显示新值时,您想更改适配器数据,您应该在 Resume 方法中初始化适配器视图并通知适配器视图,它可以帮助您重新创建具有新价值的视图。

@Override
    public void onResume() {
        super.onResume();
        if(arrayList.size()>0) {
            myShoppingCartAdapter.notifyDataSetChanged();
            getAllShoppingCartDetails();
        }

    }

我参考了你的代码,而不是我建议在适配器中使用 startActivityForResult 而不是 startActivity

 view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent detailsIntent = new Intent(context, DetailsActivity.class);
            detailsIntent.putExtra("name", currentProduct.getProduct_txt());
            detailsIntent.putExtra("quantity", currentProduct.getQuantity());
            detailsIntent.putExtra("total", total);
            context.startActivityForResult(detailsIntent, 121);
        }
    });

比起增加和减少数量比将更新的数据添加到意图和 setResult()

Intent intent = new Intent();  
intent.putExtra("MESSAGE",message);  
setResult(121,intent);
finish();

而不是在 activity

中处理你的结果
@Override  
       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
       {  
           super.onActivityResult(requestCode, resultCode, data);  
           // check if the request code is same as what is passed  here it is 2  
           if(requestCode==121)  
              {  
                String message=data.getStringExtra("MESSAGE");   
                //Do you logic like update ui, list, price 
              }  
     }  

@Yokonia Tembo,

increaseQtyButton.setOnClickListener() 侧的 DetailsActivity.java 代码中,我没有找到 MakeSales.java cartItemArrayList class

的更改过程

我认为适配器 notifyDataSetChanged() 之前那些数组列表中的更改将更新您的 CartList 中的值。

除此之外还有其他建议, 如果您正在为 ShoppingCart 应用程序工作,您应该为购物车项目创建一个数据库 table 而不是 ArrayList 您将从下面提到的一些事情中受益

  • DB table 实施将使您的购物车商品即使在关闭并重新启动应用程序后仍然可用。
  • 您可以将观察者放在 table 列更新上,这样 increasing/decreasing 值将通知 UI 更新项目

我还将在我的代码中包含 Upendra shah 的解决方案。

在编写解决方案之前,我假设您有两个活动,1. ShoppingCart.java(持有列表视图)和 DetailsActivity.java。

请按照步骤一一进行。

步骤 1. 首先从适配器中删除点击侦听器并在适配器中创建一个新方法,它将 return 您的数据列表。同时在 ShoppingCart Activity 中创建一个全局整数变量,它将保存点击的位置;

子步骤1.A 在 ShoppingCart 中如下创建全局变量 Activity

// This will be updated when user clicks on any item of listview.
int clickedPosition = -1;

子步骤1.B 创建适当的列表视图点击侦听器。

view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent detailsIntent = new Intent(context, DetailsActivity.class);
            detailsIntent.putExtra("name", currentProduct.getProduct_txt());
            detailsIntent.putExtra("quantity", currentProduct.getQuantity());
            detailsIntent.putExtra("total", total);
            context.startActivity(detailsIntent);
        }
    });

删除此代码,然后转到 ShoppingCart activity(您的列表视图对象所在的位置)。编写下面提到的代码。

yourListView.setOnItemClickListener( new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // updating clicked position variable on list item click.
            clickedPosition = position; 
            Intent detailsIntent = new Intent(ShopingCart.this, DetailsActivity.class);
            detailsIntent.putExtra("name", currentProduct.getProduct_txt());
            detailsIntent.putExtra("quantity", currentProduct.getQuantity());
            detailsIntent.putExtra("total", total);
            startActivityForResult(detailsIntent);
        }
    });

现在为将 return 您的适配器数据列表的方法编写代码。

public List<CartItems> getCartItemsFromAdapter() {
      return cartItems;
}

第 2 步。 在购物车 activity,覆盖 Activity 结果

    @Override  
           protected void onActivityResult(int requestCode, int resultCode, Intent data)  
           {  
               super.onActivityResult(requestCode, resultCode, data);  
               if(requestCode == 121)  
                  {  
                    // Update the values according to you, I am using sample key-value.
                    String updatedCost = data.getStringExtra("updatedCost");   
                    List<CartItems> cartItems = adapter.getCartItemsFromAdapter();
                    CartItems cartItemObj = cartItems.get(clickedPosition);
                    cartItemObj.setTotalCost(updatedCost);
                    adapter.notifyDataSetChanged(); // Calling this method will quickly reflect your changes to listView.
                  }  
         }  

步骤 3. 最后在您的详细信息Activity 确认按钮或您想要反映这些更改的任何按钮上,编写下面提到的代码。

confirmBtn.setOnClickListener(new OnclickListener{

Intent intent = new Intent();  
intent.putExtra("updatedCost", totalCostValue);  
setResult(121, intent);
finish();

});