如何从父活动/ Fragment2调用Fragment方法?

时间:2015-05-25 07:45:36

标签: android android-fragments

我只想通过父活动调用片段中声明的方法,它会给出错误"尝试调用虚方法' android.content.res.Resources android.content.Context.getResources()'在null对象引用"`请提出建议。

片段方法:

private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
    case 0:
        fragment = new NoticeBoard();
        break;
    case 1:
        fragment = new Quotes();
        if (fragment instanceof Quotes)
            ((Quotes) fragment).loadSpinnerData();
        break;
    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer

    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
} 

从父动作调用方法:

    var keyValue = ["personal^2", "Small^5", "Medium^7", "Large^9", "ExtraLarge^12"];
tempdata = {};
for(var i=0;i<keyValue.length;i++) {
    var key = keyValue[i].split('^')[0];
    var value = keyValue[i].split('^')[1];
    tempdata[key]= value;        
}
$scope.array = tempdata;

我的logcat如下

  

Logcat错误:java.lang.NullPointerException:尝试调用虚方法&#39; android.content.res.Resources android.content.Context.getResources()&#39;在null对象引用05-25 08:46:59.740:E / AndroidRuntime(6152):在app.redalkemi.edublaze.Quotes.loadSpinnerData(Quotes.java:210)

1 个答案:

答案 0 :(得分:0)

尝试稍微改变你的代码

setTimeout(document.getElementByID('button').click(),5000);
父活动中的

    public void loadSpinnerData(Context contxt) {
    Toast.makeText(contxt, "HELLO", Toast.LENGTH_SHORT).show();
}