我最近使用它来启动导航栏活动中的Fragment
来自Activity
(在OnListItemClick()
中):
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
getActionBar().hide();
break;
case 5:
fragment = new WhatsHotFragment();
break;
case 6:
fragment = new MyFragment();
break;
case 7:
fragment = new Views();
break;
case 8:
fragment = new editText();
break;
问题是在
之后,片段没有在Click of Button上的主要活动之上打开使用默认构造函数实例化片段。
但是现在我尝试了同样但不起作用:
MainActivity.java
MainActivity的XML有一个按钮As:
<com.gc.materialdesign.views.ButtonFlat
android:id="@+id/buttonflat"
android:onClick="startFrag"
android:layout_width="230dp"
android:layout_height="80dp"
android:layout_centerInParent="true"
android:textColor="#ffffff"
android:text="Button" />
和Java的MainActivity :(点击按钮)
public void startFrag(View v)
{
fragment = new Frag_FAB();
}
片段的java:
public class Frag_FAB extends Fragment {
public Frag_FAB() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_find_people,container,false);
return view;
}
}
Xml oF片段:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#010008"
android:layout_height="match_parent">
<TextView
android:id="@+id/txtLabel"
android:layout_width="wrap_content"
android:text="@string/stuff"
android:textColor="@color/highlighted_text_material_dark"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="16dp" />
</RelativeLayout>
答案 0 :(得分:0)
您必须将片段添加到FragmentManager。这是一个例子:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
答案 1 :(得分:0)
您需要通过FragmentTransaction
:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, fragment);
答案 2 :(得分:0)
在switch语句后添加片段事务:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, fragment);
您的代码必须是:
switch(position){
...
...
...
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
getActionBar().hide();
break;
case 5:
fragment = new WhatsHotFragment();
break;
case 6:
fragment = new MyFragment();
break;
case 7:
fragment = new Views();
break;
case 8:
fragment = new editText();
break;
...
}
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, fragment); //* Here you add the fragment! :)