[code]_[replace fragment]

1、MainActivity.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, myservice.class));
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                anotherright an = new anotherright();    //替换的碎片对象
                android.app.FragmentManager fg = getFragmentManager();    //获取碎片管理器
                android.app.FragmentTransaction fc = fg.beginTransaction();    //开启事务
                fc.replace(R.id.right_fragment, an);    //替换碎片
                fc.commit();    //提交事务


            }
        });

    }

2、被替换的碎片布局
1.activity_main.xml里给碎片分的地方,渲染到这里时,调用com.example.xiongchaochao.myapplication.right.java导入碎片布局

    

2.right 类导入布局文件layout.right_layout.xml到视图组里(activity_main.xml布局文件的布局内容就是一个视图组),展示

public class right extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        View view = inflater.inflate(R.layout.right_layout, container, false);

        return view;
    }
}

3.layout.right_layout.xml,碎片布局的内容


    

3、替换的碎片布局
1.这个时操作类,将another_right_layout.xml布局视图加入container视图组中

public class anotherright extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.another_right_layout,container,false);
        return view;
    }
}

2.碎片布局


    
    

4、上面程序运行成功后,点击返回键,会直接退出,那么怎么实现返回到上一个碎片?
addToBackStack方法

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fgobj = new anotherright();
                fgmng = getFragmentManager();
                fgtc = fgmng.beginTransaction();
                fgtc.replace(R.id.right_fragment, fgobj);
                fgtc.addToBackStack(null);  //增加的一步。事务提交前,当前状态加入栈中,点击返回会先将这个状态出栈
                fgtc.commit();
            }
        });

你可能感兴趣的:([code]_[replace fragment])