fragment_param.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8"?> <GridLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:orientation="vertical"> <TextView android:id="@+id/textView1" android:layout_marginBottom="20dp" android:textSize="20sp" /> <TextView android:id="@+id/textView2" android:textSize="20sp" /> </GridLayout> |
ParamFragment.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.phaisarn.myapplication; 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 ParamFragment extends Fragment { private String mStrArg; private int mIntArg; public ParamFragment() { // Required empty public constructor } public static ParamFragment newInstance(String strArg, int intArg) { ParamFragment frag = new ParamFragment(); Bundle bundle = new Bundle(); bundle.putString("strArg", strArg); bundle.putInt("intArg", intArg); frag.setArguments(bundle); return frag; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); mStrArg = bundle.getString("strArg"); mIntArg = bundle.getInt("intArg"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle b) { return inflater.inflate(R.layout.fragment_param, vg, false); } @Override public void onViewCreated(View view, Bundle bundle) { TextView tv1 = (TextView) view.findViewById(R.id.textView1); tv1.setText("Argument 1 ==> " + mStrArg); TextView tv2 = (TextView) view.findViewById(R.id.textView2); tv2.setText("Argument 2 ==> " + mIntArg); } } |
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity"> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/frameLayout"/> </LinearLayout> |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.phaisarn.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ParamFragment paramFragment = ParamFragment.newInstance("Android", 8); getSupportFragmentManager() .beginTransaction() .replace(R.id.frameLayout, paramFragment) .commit(); } } |