Converting an Activity to a Fragment

混江龙づ霸主 提交于 2019-11-28 14:15:16

To briefly address the problem of

I need to change from activity to fragment


Let this be the layout we want to convert. Just a simple RelativeLayout with a centered TextView. You can use the exact same layout when you convert the Activity to a Fragment. I named it fragment_layout.xml.

Of course, you will later need to change the Activity's layout to include the Fragment, but that was not the question...

<RelativeLayout 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">

    <TextView
            android:id="@+id/textView"
            android:text="Hello World"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>

Here is an Activity that we are going to convert. Notice the setContentView loads the fragment_layout.xml file and it grab out that TextView using findViewById.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

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

        textView = (TextView) findViewById(R.id.textView);
    }

}

And here is the Fragment that will act the exact same as the Activity above. Notice, now using inflate.inflate with the fragment_layout.xml file to get the View in order to grab out that TextView using rootView.findViewById.

And OnCreateView needs to return that View from the inflater.

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.TextView;

public class MainFragment extends Fragment {

    private TextView textView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_layout, container, false);

        textView = (TextView) rootView.findViewById(R.id.textView);

        return rootView;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!