此应用程序包含activity_main.xml
、mainactivit.java
和一个Fragment 类。
activity_main.xml
在RelativeLayout
中有一个Button 和FrameLayout
。
单击 Button 时,FrameLayout
应该被 fragment 替换,但它没有被替换。
activity_main.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="loadd"
android:text="Fragment No.2" />
<FrameLayout
android:id="@+id/maincontainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</RelativeLayout>
mainactivity.java
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadd(View v) {
try {
Fragment fragment = new fr();
FragmentManager frgManager = getSupportFragmentManager();
FragmentTransaction trans = frgManager.beginTransaction();
trans.replace(R.id.maincontainer, fragment);
trans.commit();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "error " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
fragment 类
public class fr extends Fragment{
public View OnCreateView(LayoutInflater inf,ViewGroup parent,Bundle save){
return inf.inflate(R.layout.send,parent, false);
}
}
发送.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textmsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 3" />
</LinearLayout>
没有编译时或运行时错误,但是当我单击该按钮时 FrameLayout
没有被 Fragment
替换。
最佳答案
您发布的所有内容看起来都不错,只是您没有覆盖 Fragment.onCreateView
,而是打错了字。
你有什么
public View OnCreateView(LayoutInflater inf, ViewGroup parent, Bundle save) {
return inf.inflate(R.layout.test, parent, false);
}
你应该拥有的东西
@Override
public View onCreateView(LayoutInflater inf, ViewGroup parent, Bundle save) {
return inf.inflate(R.layout.test, parent, false);
}
密切注意方法的名称。它应该以小写字母“o”开头。
关于Android FrameLayout 不会被 Fragments 取代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23049224/