我所做的是先创建一个tapBar(Activity)。然后在Activity下,我有第一,第二和第三个片段。我试图从第一个片段移动到下一个片段,但我得到一个空白页面(因为它不是我在xml中设置的蓝色)。有什么建议吗?
活动
public class TabBar extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
第一个片段
public class First extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.first, null);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment fragment = new Next();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(First.this);
fragmentTransaction.show(fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return rootView;
}
下一个片段
public class Next extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.next, container, false);
return rootView;
}
}
下一个片段XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/avoscloud_blue">
</RelativeLayout>
答案 0 :(得分:3)
您应该添加.add(R.id.
FragmentTransaction add(int containerViewId, 片段片段)
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Next childFrag = new Next ();
getFragmentManager().beginTransaction().add(R.id.frame_child_fragment, childFrag)
.addToBackStack(null)
.commit();
}
});
阅读Nested Fragments
以获取更多信息。
修改强>
您应该设置默认标签
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(0); // 0 is FIRST
在 FrameLayout
R.layout.first
<FrameLayout
android:id="@+id/frame_child_fragment"
android:layout_height="match_parent"
android:layout_width="match_parent"
/>
答案 1 :(得分:1)
尝试使用此方法更改fragment
:
public void changeFragment() {
Fragment fragment = new Next();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.your_layout_id, fragment);
transaction.commit();
}
答案 2 :(得分:1)
tansaction.replace()此方法适用于新片段,如果它不起作用而不是自定义寻呼机适配器并再次使用它。如果您不想创建寻呼机适配器,只需在xml中添加容器布局并将片段放入其中并在按钮上单击该片段