无法解析方法getActivity(),setArguments(),getArguments()和newInstance()

时间:2016-01-04 06:49:27

标签: android-fragments android-activity android-adapter

你能帮我解决这个错误,我不明白这是什么意思。 我正在按照教程制作标签布局 - sitepoint。这是我的代码,我将文件分开了 分为两个,主要活动(eco_detailed_information.java)并创建适配器(eco_detailed_information_adapter)

主要活动(eco_detailed_information.java) - 无法解析方法setArguments(android.os.Bundle) - 无法解析方法getActivity() - 无法解析方法getArguments()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_eco_detailed_information);

    //SET UP TOOLBAR
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);

    //Initializing NavigationView
        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);

    //NEW INSTANCE
        eco_detailed_information_adapter adapter = new eco_detailed_information_adapter(getSupportFragmentManager());

    //SET UP PAGER - TAB LAYOUT with ADAPTER
        ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewPager.setAdapter(adapter);
        TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
        tabLayout.setupWithViewPager(viewPager);
}

//DEFAULT CONSTRUCTOR
    public eco_detailed_information() {}

//
    public static eco_detailed_information newInstance(int tabPosition) {
        eco_detailed_information fragment = new eco_detailed_information();
        Bundle args = new Bundle();
        args.putInt(TAB_POSITION, tabPosition);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle args = getArguments();
        int tabPosition = args.getInt(TAB_POSITION);
        TextView tv = new TextView(getActivity());
        tv.setGravity(Gravity.CENTER);
        tv.setText("Text in Tab #" + tabPosition);
        return tv;
    }

}

适配器(eco_detailed_information_adapter) - 无法解析newInstance()

public class eco_detailed_information_adapter extends FragmentStatePagerAdapter {

    public eco_detailed_information_adapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return eco_detailed_information_adapter.newInstance(position);
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Tab " + position;
    }
}

}

1 个答案:

答案 0 :(得分:0)

示例工作正常,但您提供的代码有一些错误,例如:在您的适配器中,您返回 eco_detailed_information_adapter newInstance(),这是错误的!你应该返回碎片的newInstance。

您应该创建一个类似示例(DesignDemoFragment)将它放在活动或单独的类中(如果您想将它放在单独的类中,您应该进行一些更改)然后将newInstance()放入其中。