Fragment创建一个Activity对象,但它为null

时间:2015-07-06 00:15:11

标签: android android-fragments android-activity

在我的fragment类中,我创建了一个Activity类的对象:

MainActivity mainActivity;

在我的片段OnCreateView()中,我将其初始化:

mainActivity = new MainActivity();

但是,当我调试我的应用时,mainActivity始终为空。这是为什么?

我的活动课程:

package com.example.brettrosen.atls;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;


@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
public ActionBar actionBar;

// Tab titles
private String[] tabs = {"Pre-arrival Plan", "Primary Survey", "Secondary Survey"};

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initialization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

    updateTabTitles(0, 12);
    updateTabTitles(1, 2);
    updateTabTitles(2, 14);
}

public void updateTabTitles(int pageNum, int remaining) {
    String text = tabs[pageNum] + " (" + remaining + ")";
    System.out.println(actionBar);

    actionBar.getTabAt(pageNum).setText(text);
}


@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

}


};

1 个答案:

答案 0 :(得分:1)

我发现您的问题是您要从其托管的片段中访问getActivity();

要做到这一点,你可以这样称呼:

MainAcitvity

它将返回您的MainActivity yourMain = (MainActivity) getActivity(); yourMain.method1(); (或当前托管您片段的任何其他活动)。

要从中访问方法,您必须转换该方法的返回值。

{{1}}

请记住在片段中执行此操作。