请帮忙。 在开发了一个界面以便在片段之间进行通信"计算器" (发送信息)和" ShoppingList" (接收信息)我似乎无法将信息添加到我的ArrayList中。我知道这些信息是通过发送的,但我似乎无法将其添加到列表中,以便将其合并到我的列表视图中。 而且,我不应该。如果我硬编码信息 例如: myItems.add(new ListItems(R.drawable.thrash," Cornflakes",1,50.00,60.00)); 它工作正常
请帮助。
Calculator.java
public class Calculator extends Fragment {
private static EditText ItemText, Editcost, Editquantity, Calcost, Rtax;
private static RadioGroup rgroup;
CalculatorListener activityCommander;
public interface CalculatorListener{
public void addtoCart(String itemName, int qty, double beforeTax, double afterTax);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (CalculatorListener) context;
}catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}
public Calculator() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_calculator, container, false);
Editcost = (EditText)view.findViewById(R.id.editcost);
ItemText = (EditText)view.findViewById(R.id.itemText);
Editquantity = (EditText)view.findViewById(R.id.editquantity);
Calcost = (EditText)view.findViewById(R.id.calcost);
Rtax = (EditText)view.findViewById(R.id.rtax);
rgroup = (RadioGroup)view.findViewById(R.id.rgroup);
final ImageButton FieldButton = (ImageButton)view.findViewById(R.id.FieldButton);
final ImageButton TaxButton = (ImageButton)view.findViewById(R.id.TaxButton);
final ImageButton CalButton = (ImageButton)view.findViewById(R.id.CalButton);
Rtax.setEnabled(false);
Calcost.setEnabled(false);
ItemText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
v.setBackgroundResource(R.drawable.edittxt);
} else {
v.setBackgroundResource(R.drawable.edittxtfocus);
}
}
}
);
Calcost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundResource(R.drawable.edittxtfocus);
} else {
v.setBackgroundResource(R.drawable.edittxt);
}
}
}
);
Editcost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundResource(R.drawable.edittxtfocus);
} else {
v.setBackgroundResource(R.drawable.edittxt);
}
}
}
);
Editquantity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundResource(R.drawable.edittxtfocus);
} else {
v.setBackgroundResource(R.drawable.edittxt);
}
}
}
);
CalButton.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
results(v);
}
}
);
return view;
}
public void results (View view)
{
double taxValue = Double.parseDouble(Rtax.getText().toString()), cost = 0, newCost = 0;
int quantity = 1, radiobuttonID = rgroup.getCheckedRadioButtonId(), index;
String item = ItemText.getText().toString();
//FIELD VALIDATIONS
if(Editcost.getText().toString().isEmpty())
{
Toast show = Toast.makeText(getActivity(), "Cost is required!", Toast.LENGTH_SHORT);
show.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
show.show();
}
//CHECKS THE TAX VALUE IF IT NEEDS TO BE CONVERTED
if (taxValue > 1)
{
taxValue = taxValue / 100;
}
else
{
taxValue = taxValue * 1;
}
//CUSTOM VALIDATOR FOR QUANTITY FIELD
if (Editquantity.getText().toString().isEmpty())
{
quantity = 1;
}
else if (!Editquantity.getText().toString().isEmpty())
{
quantity = Integer.parseInt(Editquantity.getText().toString());
}
//DECIDE WHETHER TO USE TAX INCLUDED OR EXCLUDED
View radioButton = rgroup.findViewById(radiobuttonID);
index = rgroup.indexOfChild(radioButton);
if(index == 0)
{
newCost = (((cost = Double.parseDouble(Editcost.getText().toString())) * taxValue) + cost) * quantity;
}
else if (index == 1)
{
newCost = ((cost = Double.parseDouble(Editcost.getText().toString())) * quantity);
}
//PRINTS NEW COST TO SCREEN
Calcost.setText("" + newCost);
//CUSTOM HINT POP UP
if(!item.isEmpty())
{
Toast show = Toast.makeText(getActivity(), item+" was added to cart", Toast.LENGTH_LONG);
show.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
activityCommander.addtoCart(item, quantity, cost, newCost);
show.show();
}else if(item.isEmpty() & !Editcost.getText().toString().isEmpty())
{
if (index == 0 || index == 1)
{
Toast show = Toast.makeText(getActivity(),"Item was added to cart", Toast.LENGTH_LONG);
show.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
activityCommander.addtoCart(item, quantity, cost, newCost);
show.show();
}
}
}
}
Core.java
public class Core extends AppCompatActivity implements Calculator.CalculatorListener{
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.core);
toolbar = (Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
viewPager = (ViewPager)findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new Calculator(),"Calculator");
viewPagerAdapter.addFragments(new ShoppingList(), "Shopping Cart");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public void addtoCart(String itemName, int qty, double beforeTax, double afterTax) {
ShoppingList mShoppingList = (ShoppingList) getSupportFragmentManager().findFragmentById(R.id.ShopFrag);
if(mShoppingList != null)
{
mShoppingList.populatelist(itemName, qty, beforeTax, afterTax);
}
else{
Log.e(Tag,"Cart is Null");
}
}
ShoppingList.java
package com.sta.salestaxaccumulator;
import android.app.LauncherActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class ShoppingList extends Fragment {
public List<ListItems> myItems = new ArrayList<ListItems>();
public ShoppingList() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_shopping_list, container, false);
populatelistview(view);
//setCart();
return view;
}
public void populatelist(String itemName, int qty, double beforeTax, double afterTax)
{
myItems.add(new ListItems(R.drawable.thrash, itemName, qty, beforeTax, afterTax));
//myItems.add(new ListItems(R.drawable.thrash, "Cornflakes", 1, 50.00, 60.00));
/*Toast show = Toast.makeText(getActivity(),itemName+" is here", Toast.LENGTH_LONG);
show.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
show.show();*/
}
/*public void setCart(String itemName, int qty, double beforeTax, double afterTax)
{
//myItems.add(new ListItems(R.drawable.thrash, "Cornflakes", 1, 50.00, 60.00));
//myItems.add(new ListItems(R.drawable.thrash, "Cheese", 1, 80.00, 90.00));
//myItems.add(new ListItems(R.drawable.thrash, "Rice", 1, 40.00, 70.00));
//myItems.add(new ListItems(R.drawable.thrash, "Oatmeal", 2, 35.00, 62.00));
}*/
public void populatelistview(View view)
{
ArrayAdapter<ListItems> adapter = new MyListAdapter();
ListView listView = (ListView)view.findViewById(R.id.listView);
listView.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<ListItems>
{
public MyListAdapter()
{
super(getActivity(), R.layout.custom_row, myItems);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Ensures we have a view to work with (may have been given null)
View itemView = convertView;
if (itemView == null) {
itemView = getActivity().getLayoutInflater().inflate(R.layout.custom_row, parent, false);
}
//Finds the item to work with
ListItems currentitem = myItems.get(position);
//Fills the view
ImageView imageView = (ImageView) itemView.findViewById(R.id.Thrash);
imageView.setImageResource(currentitem.getIconID());
//Item Name
TextView name = (TextView) itemView.findViewById(R.id.ItemName);
name.setText(currentitem.getItemName());
//Item Qty
TextView qty = (TextView) itemView.findViewById(R.id.QuantityValue);
qty.setText("" + currentitem.getQty());
//Before Tax
TextView btax = (TextView) itemView.findViewById(R.id.BeforeTaxValue);
btax.setText("" + currentitem.getBeforeTax());
//After Tax
TextView atax = (TextView) itemView.findViewById(R.id.AfterTaxValue);
atax.setText("" + currentitem.getAfterTax());
imageView.setTag(currentitem);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myItems.remove(myItems.get(position));
notifyDataSetChanged();
}
});
return itemView;
}
}
}
ListItems.java
package com.sta.salestaxaccumulator;
public class ListItems {
private int IconID;
private String ItemName;
private int Qty;
private double BeforeTax, AfterTax;
public ListItems(int iconID, String itemName, int qty, double beforeTax, double afterTax) {
IconID = iconID;
ItemName = itemName;
Qty = qty;
BeforeTax = beforeTax;
AfterTax = afterTax;
}
public int getIconID() {
return IconID;
}
public String getItemName() {
return ItemName;
}
public int getQty() {
return Qty;
}
public double getBeforeTax() {
return BeforeTax;
}
public double getAfterTax() {
return AfterTax;
}
}
Core.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
xmlns:tools2="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sta.salestaxaccumulator.Core">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="@+id/AppBarFrag">
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="@layout/toolbar_layout"/>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tabLayout"
app:tabMode="fixed"
app:tabGravity="fill">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewPager"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/AppBarFrag">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.sta.salestaxaccumulator.Calculator"
tools2:layout="@layout/fragment_calculator"
android:id="@+id/CalcuFrag" />
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.sta.salestaxaccumulator.ShoppingList"
tools2:layout="@layout/fragment_shopping_list"
android:id="@+id/ShopFrag"/>
</android.support.v4.view.ViewPager>
</RelativeLayout>
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter{
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragments, String titles)
{
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
答案 0 :(得分:1)
在调用其中一种方法之前,您应检查购物车是否为空。
ShoppingList cart = (ShoppingList)getSupportFragmentManager().findFragmentById(R.id.shoppinglistfrag);
if(cart != null){
cart.setCart(view,itemName,qty,beforeTax,afterTax);
}
else{
Log.e(TAG, "null cart");
}
来自FragmentManager文档:
查找由给定id标识的片段 在XML中膨胀或在事务中添加时作为容器ID。 这首先搜索当前添加到的片段 经理的活动;如果没有找到这样的片段,那么所有片段 当前在与此ID相关联的后台堆栈上进行搜索。
因此,似乎您从未创建或使用过ShoppingList片段,因此FragmentManager无法找到它。
尝试将ShoppingList作为本地变量添加到您的Activity中,并在MainActivity onCreate中初始化它...
public class Core extends AppCompatActivity implements Calculator.CalculatorListener{
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
ShoppingList mShoppingList;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
...
mShoppingList = new ShoppingList();
}
@Override
public void addtoCart(View view,String itemName, int qty, double beforeTax, double afterTax) {
mShoppingList.setCart(view,itemName,qty,beforeTax,afterTax);
}
}
编辑:
对于您的ShoppingList类,请创建ListView
和ArrayAdapter
类变量。然后,您可以使用populatelist()
方法访问它们。将商品添加到您的列表后,请致电adapter.notifyDataSetChanged()
。
注意: 将来,提出一个新问题,不要完全改变现有问题。对于将来寻找答案的其他人而言,这会让人感到困惑。