我试图通过单击MainActivity中的按钮将片段放入MainActivity的FrameLayout
中。它几乎可以工作,但是MainActivity的public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.pushMeBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager f_m = getSupportFragmentManager();
FragmentTransaction f_t = f_m.beginTransaction();
f_t.replace(R.id.container_layout, new Fragment1()).addToBackStack(null).commit();
}
});
}
}
的内容不会被Fragment内容代替,而是添加到其中。所以问题是:如何使其正确?
我的MainActivity类
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/container_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/pushMeBtn"
android:text="push me"
android:layout_gravity="center"/>
</FrameLayout>
</RelativeLayout>
我的activity_main.xml
public class Fragment1 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container,false);
}
}
我的Fragment1类
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="339dp"
android:gravity="center"
android:text="fragment1"
android:textSize="25sp"/>
</RelativeLayout>
我的fragment.xml
{{1}}