fragment_demo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"/>
</LinearLayout>
MyFragment
package com.example.test28;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
@SuppressLint("NewApi")
public class MyFragment extends Fragment{
private TextView text;
private int count;
public static MyFragment newInstance(int num){
Bundle bundle=new Bundle();
bundle.putInt("count", num);
MyFragment f=new MyFragment();
f.setArguments(bundle);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle=getArguments();
count=(Integer) bundle.get("count");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_demo, null);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
text=(TextView) view.findViewById(R.id.tv_textView);
text.setText("fragment#"+count);
//super.onViewCreated(view, savedInstanceState);
}
}
activity_main.xml
<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"
>
<LinearLayout
android:id="@+id/layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
></LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="replaceOnclick"/>
</LinearLayout>
MainActivity.java
package com.example.test28;
import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class MainActivity extends ActionBarActivity {
private int num=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@SuppressLint("NewApi")
public void replaceOnclick(View view){
num++;
MyFragment fragment=MyFragment.newInstance(num);
getFragmentManager().
beginTransaction().
replace(R.id.layout, fragment).
commit();
}
}