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

时间:2017-10-03 07:17:21

标签: java android listview arraylist android-adapter

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

MakeSale.java中,我宣布了两个数组列表,即客户要购买的第一个cartItemArrayList商店商品。这些是生产者名称,产品名称,数量,unitCost和第二个,cartCostItemsList包含购物车中商品的总成本。

内部MakeSale.java

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

然后我有一个扩展ArrayAdapter的适配器类。此类链接到列表视图上显示的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的类中,如意图所示。当然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);
            }
        });
    }
  }
}

现在,当用户点击list_item时,如何在列表视图的confirmChangesBtn中设置/替换这些新值(新数量,新的totalCost)?通过这样做更改数组列表中的产品详细信息(cartItemArrayListcartCostItemsList)。将textview值从DetailsActivity.java传递到适配器以进行显示?我该怎么做?任何人?

4 个答案:

答案 0 :(得分:0)

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

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

    }

答案 1 :(得分:0)

我推荐您的代码,而不是我建议在适配器中使用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();

比在活动中处理结果

@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 
              }  
     }  

答案 2 :(得分:0)

@Yokonia Tembo,

在我DetailsActivity.java旁边increaseQtyButton.setOnClickListener()的代码中,我找不到cartItemArrayList MakeSales.java类<{1}}的更改过程

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

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

  • 即使在杀死并重新启动应用程序后,数据库表实现也会使您的购物车项目可用。
  • 您可以将观察者放在表列更新中,以便增加/减少值将通知UI更新项目

答案 3 :(得分:0)

我还会在我的代码中加入Upendra shah的解决方案。

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

请逐一按照步骤操作。

第1步。首先从适配器&amp;中删除点击侦听器。在适配器中创建一个新方法,它将返回您的数据列表。还要在ShoppingCart Activity中创建一个全局整数变量,它将保持点击的位置;

子步骤1.A 在ShoppingCart活动中创建如下所示的全局变量

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

子步骤1.B 创建正确的listview点击监听器。

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活动(列表视图对象存在的位置)。写下面提到的代码。

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);
        }
    });

现在为返回适配器datalist的方法编写代码。

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

第2步。在购物车活动中,覆盖onActivityResult

    @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步。最后,在您的DetailsActivity确认按钮或任何想要反映这些更改的按钮上,写下以下提到的代码。

confirmBtn.setOnClickListener(new OnclickListener{

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

});