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;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…