![](/img/trans.png)
[英]How do you pass values from an activity to a class in Android Studio?
[英]Android - How do you pass textview values from Activity-A to an adapter
我正在開發一個購物車應用程序,我需要一些有關適配器的幫助。 我試圖在這里回答類似的問題,但這與我的情況有些不同。 我有3個類: MakeSale.java
, DetailsActivity.java
和ShoppingCartListAdapter.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
的類中。 當然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)設置/替換到列表視圖的list_item
? 通過這樣做,可以更改數組列表( cartItemArrayList
和cartCostItemsList
)中的產品詳細信息。 將DetailsActivity.java
值從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);
}
});
比增加和減少數量時要多,而不是將更新后的數據添加到intent和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
}
}
@Yokonia Tembo,
在您的側面increaseQtyButton.setOnClickListener()
DetailsActivity.java
increaseQtyButton.setOnClickListener()
的DetailsActivity.java
代碼中,我沒有找到MakeSales.java
類的cartItemArrayList
的更改過程。
我認為在適配器的notifyDataSetChanged()
之前更改那些數組列表會更新CartList中的值。
除此以外,還有其他建議,如果您正在使用ShoppingCart應用,則應該為購物車商品創建一個數據庫表而不是ArrayList,您將受益於以下幾項內容
我還將在代碼中包含Upendra shah的解決方案。
在編寫解決方案之前,我假設您有兩個活動,分別是:1. ShoppingCart.java(保留列表視圖)和DetailsActivity.java。
請一一遵循。
步驟1.首先從適配器中刪除Click偵聽器,並在適配器中創建一個新方法,該方法將返回您的數據列表。 還要在ShoppingCart Activity中創建一個全局整數變量,該變量將保留被點擊的位置;
子步驟1.A在ShoppingCart活動中創建如下所示的全局變量
// This will be updated when user clicks on any item of listview.
int clickedPosition = -1;
子步驟1.B創建適當的listview Click監聽器。
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活動(存在listview對象的位置)。 寫下面提到的代碼。
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);
}
});
現在,為將返回適配器數據列表的方法編寫代碼。
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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.