首先,我知道已经在这里回答了这个问题:Android communication between fragment and baseadapter,我尝试实现它,但是由于这是我第一次使用接口,并且没有得到其背后的逻辑,所以它没有用。我的问题是我想设置此片段的TextView的值
Fragment.java
public class FragmentCart extends Fragment {
private TextView totalTxt;
private TextView totalItems;
private ListView itemList;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
totalTxt = (TextView)view.findViewById(R.id.totalTxt);
totalItems = (TextView)view.findViewById(R.id.totalItems);
itemList = (ListView)view.findViewById(R.id.itemList);
itemList.setAdapter(MainActivity.cart);
return view;
}
}
具有该适配器的值(双totalCost)
Adapter.java
public class Cart extends BaseAdapter {
private double totalCost = 0;
public getView() {
Item item.....
totalCost += item.getPrice();
}
}
逻辑是,当我将项目添加到购物车(适配器)时,片段中的TextView也将更新。如何使用界面执行此操作?
答案 0 :(得分:0)
直接回答您的问题:
在 Adapter.java 中声明一个我们称为TotalCostUpdater
的新接口:
public interface TotalCostUpdater {
void onTotalCostUpdated(int totalCost);
}
然后,仍然在适配器中,您需要一个通过构造函数初始化实现此接口的字段。更新值后,您可以从那里调用onTotalCostUpdated(totalCost)
。
您的 Adapter.java 类将如下所示:
public class Cart extends BaseAdapter
{
public interface TotalCostUpdater {
void onTotalCostUpdated(int totalCost);
}
private double totalCost = 0;
private TotalCostUpdater costUpdater;
public Cart(TotalCostUpdater costUpdater) {
this.costUpdater = costUpdater;
}
public getView()
{
Item item.....
totalCost += item.getPrice();
costUpdater.onTotalCostUpdated(totalCost);
}
}
然后,您需要实现TotalCostUpdater
,并在 FragmentCart.java 中覆盖其onTotalCostUpdated
方法:
public class FragmentCart extends Fragment implements Cart.TotalCostUpdater
{
private TextView totalTxt;
private TextView totalItems;
private ListView itemList;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_cart, container, false);
totalTxt = (TextView)view.findViewById(R.id.totalTxt);
totalItems = (TextView)view.findViewById(R.id.totalItems);
itemList = (ListView)view.findViewById(R.id.itemList);
itemList.setAdapter(MainActivity.cart);
return view;
}
@Override
public void onTotalCostUpdated(int totalCost) {
totalTxt.setText(totalCost);
}
}
在实例化适配器时(有时必须写一个new Cart()
),您需要传递FragmentCart
,它现在正在实现Cart
中预期的接口” s的构造函数:
new Cart(fragmentCart);
这应该可以解决问题。这是您应该考虑的其他事项:
CartData
类来保存实际的购物车值。MainActivity.cart
中的全局适配器。您应该直接在Fragment类中实例化它findViewById
呼叫。