Android Studio从其他片段或活动中调用片段方法 [英] Android Studio call fragment method from other fragment or activity

查看:115
本文介绍了Android Studio从其他片段或活动中调用片段方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关此问题的新问题: Android Studio刷新错误

我想从另一个片段中调用片段中的Method.我已经尝试过:

I want call a Method in a Fragment from another Fragment. I have already tried this:

(Tab3Storage) (getSupportFragmentManager().findFragmentById(R.id.tab3storage)).Storagerefresh();

但是我有一个NullPointerException错误.我该如何进行此调用或将其作为Fragment的活动,因为从Fragment到Activity的调用已经可以了.

but I have a NullPointerException error. How I can make this or a calling form a activity to the Fragment, because the calling from the Fragment to the Activity works already fine.

代码:

主要活动:

public void refreshAll(){

    Tab3Storage tab3Storage = new Tab3Storage();
    tab3Storage.Storagerefresh();

    Tab4Gravel tab4Gravel = new Tab4Gravel();
    tab4Gravel.Gravelrefresh();
}

这是片段代码:

totalMoney = loadData("totalMoney");
    totalMoneyDisplay.setText("$ " + totalMoney);

    totalGravel = loadData("totalGravel");
    totalGravelDisplay.setText(totalGravel + " Gravel");

    Storage_Level = loadData("storageLevel");
    if (Storage_Level == 0){
        Storage_Level = 1;
    }
    if(Storage_Level == 1){
        Storage_Capacity = Storage_Level1;
    }
    if(Storage_Level == 2){
        Storage_Capacity = Storage_Level2;
    }
    if(Storage_Level == 3){
        Storage_Capacity = Storage_Level3;
    }
    if(Storage_Level == 4){
        Storage_Capacity = Storage_Level4;
    }
    saveData("storageLevel", Storage_Level);

    Storage_Filled = totalGravel;
    storageCapacityDisplay.setText(Storage_Filled + "/" + Storage_Capacity);
    SellGravelButton.setText("Sell: $" + totalGravel);

    storageUpgradebtn.setText("Level " + Storage_Level + ":\n$" + Storage_Capacity / 2 );

加载数据代码:

private long loadData(String name){

    SharedPreferences shared = this.getActivity().getPreferences(Context.MODE_PRIVATE);
    long value = shared.getLong(name, 0);
    return value;
}

推荐答案

使用此getSupportFragmentManager().findFragmentById(R.id.tab3storage))告诉Android的是获取片段的视图,而不是片段的代码

What your telling android with this getSupportFragmentManager().findFragmentById(R.id.tab3storage)) is to get the view of the fragment, not actually the code of it

为此,只需创建片段并调用函数:

To do that simply create the fragment and call the function:

myFragment fragment = new myFragment();
fragment.Storagerefresh();

这篇关于Android Studio从其他片段或活动中调用片段方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆