应用程序启动时会显示片段(onCreate),但恢复时会显示片段(onResume)

时间:2017-03-05 04:24:08

标签: java android android-fragments

我遇到的问题是,当应用程序最初启动时(在主应用程序onCreate方法期间),我的主要活动中的片段不会显示,但是当我暂停应用程序然后恢复它时会显示(在此期间) onResume方法)

这是我主要活动的重要部分 activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/activity_main"
    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" />               

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

MainActivity:

public class MainActivity extends Activity {

    protected FrameLayout fragment_container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (findViewById(R.id.fragment_container) != null) {
            if (savedInstanceState != null) {
                TextViewFragment fragment = new TextViewFragment();
                fragment.setArguments(getIntent().getExtras());

                getFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();
            }
        }}

TextViewFragment:

public class TextViewFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.textview_fragment, container, false);
    }

}

textview_fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="This is not showing up"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:typeface="sans"
        android:textSize="35sp"/>
</LinearLayout>

感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

当它首先启动时,if(savedInstanceState!= null){condition给出null。

您可以删除条件,然后它将始终加载片段。