我的 Android 项目面临一个问题,我试图在一个 Activity 中显示两个 XML 布局并使用片段在它们之间切换。这是我的设置的细分:
1.活动结构:我的项目中有一个活动(ActivityMenuIcon)。
2.布局:
第一个 XML 布局 (activity_menu_menu.xml) 包含一个按钮。单击此按钮后,我想显示另一个 XML 布局的迷你表单。 单击按钮后应该会显示第二个 XML 布局 (fragment1.xml)。
3.Fragment 实现:我尝试通过在 Activity 中实现 Fragment 来实现此功能。这是我的 Java 代码的简化版本:
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class ActivityMenuIcon extends AppCompatActivity {
Button addbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_menu);
addbutton = findViewById(R.id.addBtt);
addbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
replaceFragment(new fragment1());
}
});
}
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.layout1, fragment);
fragmentTransaction.commit();
}
}
4.XML布局:
activity_menu_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="@+id/layout1"
tools:context=".fragment1">
<!-- Comment: XML code here -->
</FrameLayout>
fragment1.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".fragment2">
<!-- Comment: XML code here -->
</FrameLayout>
尽管我付出了努力,但在单击第一个布局 (activity_menu_menu.xml) 中的按钮后,我仍无法成功显示第二个 XML 布局 (fragment1.xml)。预期的行为是,单击按钮后,包含fragment1.xml 的片段应替换当前布局。 对于如何使用片段正确实现此功能的任何见解或建议,我将不胜感激。如果我的方法有任何错误或需要改进,请告诉我。谢谢您的协助!
看来我误解了fragment的功能,发现可以这样完成:
Button addButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_menu);
addButton = findViewById(R.id.addBtt);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
show();
}
});
}
private void show() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.activity_menu_todo_pop_up);
dialog.show();
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setGravity(Gravity.BOTTOM);
}