像这样的参数
adapter.addFragment(new Tab1Fragment(), "TAB 1");
adapter.addFragment(new Tab2Fragment(), "TAB2");`
使用Tab Fragment
主要活动
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "TAB 1");
adapter.addFragment(new Tab2Fragment(), "TAB2");
adapter.addFragment(new Tab3Fragment(), "TAB3");
viewPager.setAdapter(adapter);
}
}
章节页适配器
class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
}
片段tab1
public class Tab1Fragment extends Fragment {
private static final String TAG = "Tab1Fragment";
private Button btntestBin1;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment,container,false);
btntestBin1 = (Button) view.findViewById(R.id.btntestBin1);
btntestBin1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Testing Button click 1", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
我正在尝试传递addFragment()参数,但是会出现这样的错误,
更改方法的第一个参数&#39; addFragment&#39;来自&#39; Fragment&#39;至 &#39; Tab1Fragment&#39;
答案 0 :(得分:1)
更改此
import android.app.Fragment;
到
import android.support.v4.app.Fragment;
Tab1Fragment
中的。同样检查所有导入。您需要使用support lib中的Fragment