[英]How to call an activity method from a fragment?
我需要从片段调用活动中的方法,我什至无法实例化片段中的活动,我不知道如何解决这个问题。 我需要从作为片段一部分的 onClick 调用活动的方法,因为我需要更新一个值,因为它发生了变化(例如:值为 1,在 onClick 之后值为 2,但活动不更新)。
这是活动中的方法:
public void onUpdate(){
//setCount.setText(Integer.toString(new Database(this).getCountCart(FirebaseAuth.getInstance().getCurrentUser().getUid())));
setCount.setText(Integer.toString(new Database(this).getTotalCount(FirebaseAuth.getInstance().getCurrentUser().getUid())));
cart = new Database(this).getCarts(FirebaseAuth.getInstance().getCurrentUser().getUid());
int total = 0;
for(OrderModel order:cart)
total+=(Integer.parseInt(String.valueOf(order.getPret()))) *(order.getCantitate());
Locale locale = new Locale("ro","RO");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
totalPrice.setText(fmt.format(total));
}
这是我尝试从片段中调用它的地方:
fragmentItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Database(getActivity().getBaseContext()).increaseCart(FirebaseAuth.getInstance().getCurrentUser().getUid(),fragmentUnuModel.getDenumire());
food.onUpdate();
}
这是错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.cosnila.orderme.Food.onUpdate()' on a null object reference
at com.cosnila.orderme.Fragments.FragmentUnu$1$1.onClick(FragmentUnu.java:123)
如果您的活动中有方法onUpdate并想从片段调用活动方法,请在需要时在片段中按如下方式调用它。
((YouActivityName) getActivity()).onUpdate();
请务必替换您的活动名称。
img_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent displayFlights = new Intent(getActivity(), SelectFlight.class);
startActivity(displayFlights);
}
});
您可以将 onUpdate() 设为static
。
您的方法标头应如下所示:
public static void onUpdate() {
// your code
}
如果你使用的是 Kotlin 而不是 java 你应该试试这个
(activity as yourActivityName?)?.yourPublicMethod()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.