如何在应用启动时加载片段



我创建了一个基本上具有导航抽屉的应用程序,我希望在活动启动而不是主活动时加载一个片段"主页"。 任何知道怎么做。

可以调用此方法查看片段。在您的情况下,请在onCreate()上调用此方法

//Fragment Changer
public void changeFragment(Fragment targetfragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_fragment, targetfragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commitAllowingStateLoss();
}

示例用法

changeFragment(new YourFragment());

基本解决方案可以在onCreate方法中实现类似于以下代码的内容。

// get fragment manager
FragmentManager fm = getFragmentManager();
// replace
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_layout, new HomeFragment());
ft.commit();

您的活动:

public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public String getHelloMessage() {
return "Hello!";
}
}

您的观点:

public class MainView extends Fragment {
// Declarations
private Button testButton;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_view, container, false);
// Getting the reference of controller from Application
MainController mainController = Application.getInstance().getMainController();
// Initializing view objects
testButton = view.findViewById(R.id.test_button);
// Setting actions
testButton.setOnClickListener(mainController.getTestAction());
return view;
}
// Reference to the view Object
public Button getTestButton() {
return testButton;
}

您的 main_activity.xm lto 连接片段

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/containerMainView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/mainView"
android:name="com.template.views.MainView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>

您的main_view.xml提交最终视图定义

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/test_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/say_hello" />
</RelativeLayout>

最新更新