小编Maa*_*usa的帖子

运行片段事务一旦打开,就会停止应用程序

如果我在事务中删除.commit(),应用程序将编译但显示空屏幕.如果我添加.commit(),应用程序会立即打开和关闭.我是片段新手,任何人都可以帮助解决这个问题.我只是添加了一个ImageView布局.在Fragment类中对其进行实施,并在其中硬编码图像.此外,我刚刚在MainActivity中创建了一个Fragment实例.

我的Android Studio版本是:3.1.3

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
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=".MainActivity">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="180dp"
android:id="@+id/head_container"
/>


</android.support.constraint.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

body_part_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" 
android:layout_height="match_parent"
android:id="@+id/body_part_frag"
>

</ImageView>
Run Code Online (Sandbox Code Playgroud)

BodyPartFragment.java

 package com.example.musa.my_frag_app;

 import android.os.Bundle;
 import android.support.v4.app.Fragment;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;

public class BodyPartFragment extends Fragment {

public BodyPartFragment(){
    //Do Nothing
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

    View rootView = inflater.inflate(R.layout.body_part_fragment, container);
    ImageView body_image = rootView.findViewById(R.id.body_part_frag);
    body_image.setImageResource(R.drawable.ic_launcher_background);

  return rootView;
}

}
Run Code Online (Sandbox Code Playgroud)

MainActivity.java …

android android-fragments

0
推荐指数
1
解决办法
42
查看次数

标签 统计

android ×1

android-fragments ×1