这是我的导入样本
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
这就是我使用Fragment
的地方private void SetUpViewPager(ViewPager viewpager) {
/*Creating a tab adapter*/
TabAdapter adapter = new TabAdapter(getSupportFragmentManager());
adapter.AddFragment(new Fragment1(),"Activity");
adapter.AddFragment(new Fragment2(),"Friends");
adapter.AddFragment(new Fragment3(),"Inbox");
/*Set the adapter to the view pager property*/
viewpager.setAdapter(adapter);
}
我收到错误的第一个参数发现Fragment1 Required Fragment2
这是适配器类 我不确定问题出在哪里 在代码中 下面 私有类TabAdapter扩展了FragmentPagerAdapter {
private ArrayList<Fragment> Fragments;
ArrayList<String> FragmentNames;
/*Constructor*/
TabAdapter(FragmentManager fm) {
super(fm);
Fragments = new ArrayList<>();
FragmentNames = new ArrayList<>();
}
/*Helper method which adds a fragment which in turn adds a tab*/
void AddFragment(Fragment1 fragment, String name) {
Fragments.add(fragment);
FragmentNames.add(name);
}
/*Get the current item of the tab its on*/
@Override
public Fragment getItem(int position) {
return Fragments.get(position);
}
/*Returns the number of fragments that are in this adapter*/
@Override
public int getCount() {
return Fragments.size();//Check on This
}
@Override
public CharSequence getPageTitle(int position)
{
return FragmentNames.get(position);
}
}
答案 0 :(得分:1)
AddFragment()期待 Fragment1 作为第一个参数。所以错误是显而易见的。
/*Helper method which adds a fragment which in turn adds a tab*/
void AddFragment(Fragment1 fragment, String name) {
Fragments.add(fragment);
FragmentNames.add(name);
}
如果你想让你的方法接受多个类,那么你有两个选择。
将AddFragment()
接受Fragment
作为第一个参数
addFragment(Fragment fragment, String name)
声明一个接口并使您的类符合该接口,并将该接口用作参数。
public interface FragmentInterface{
// You can declare common functionalities here
}
public class Fragment1 extends Fragment implements FragmentInterface {
// Class implementation
}
/*Helper method which adds a fragment which in turn adds a tab*/
void AddFragment(FragmentInterface fragment, String name) {
Fragments.add(fragment);
FragmentNames.add(name);
}