簡體   English   中英

如何從片段調用活動方法?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM