1 import java.util.Date; 2 import java.util.LinkedList; 3 4 import com.qianfeng.gp08_day23_fragment5.fragment.TestFragment; 5 6 import android.os.Bundle; 7 import android.app.Activity; 8 import android.app.Fragment; 9 import android.app.FragmentTransaction; 10 import android.view.Menu; 11 import android.view.View; 12 13 /** 14 * 15 * 16 * 17 */ 18 public class MainActivity_2 extends Activity { 19 20 @Override 21 protected void onCreate(Bundle savedInstanceState) { 22 super.onCreate(savedInstanceState); 23 setContentView(R.layout.activity_main); 24 } 25 26 public void addFragment(View v) { 27 TestFragment fragment = new TestFragment(); 28 Bundle bundle = new Bundle(); 29 bundle.putString("msg", "xixi" + new Date()); 30 fragment.setArguments(bundle); 31 32 FragmentTransaction tran = getFragmentManager().beginTransaction(); 33 34 tran.add(R.id.container, fragment);//remove1 add 2 35 36 tran.addToBackStack(null);//把事务加入当前的回退栈 回滚 37 38 tran.commit(); 39 } 40 41 // 点击回退按钮显示上一个fragment 42 public void backFragment(View v) { 43 44 onBackPressed(); 45 } 46 }
MainActivity
1 import android.app.Activity; 2 import android.app.Fragment; 3 import android.graphics.Color; 4 import android.os.Bundle; 5 import android.view.LayoutInflater; 6 import android.view.View; 7 import android.view.ViewGroup; 8 import android.widget.TextView; 9 10 public class TestFragment extends Fragment { 11 12 private String args; 13 14 @Override 15 public void onAttach(Activity activity) { 16 args = getArguments().getString("msg"); 17 super.onAttach(activity); 18 } 19 20 @Override 21 public View onCreateView(LayoutInflater inflater, ViewGroup container, 22 Bundle savedInstanceState) { 23 TextView textView = new TextView(getActivity()); 24 textView.setText(args); 25 int red = (int)(Math.random()*256); 26 int green = (int)(Math.random()*256); 27 int blue = (int)(Math.random()*256); 28 29 textView.setBackgroundColor(Color.rgb(red, green, blue)); 30 return textView; 31 } 32 33 }
TestFragment
此方法是动态创建fragment
时间: 2024-10-25 05:05:06