使用

动态使用

getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.title_layout,new TitleFragment())
                        .commit();

V4包

动态切换

Random random = new Random();
                if (random.nextBoolean()){
                    getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.title_layout,new TitleFragment())
                            .commit();
                }else{
                    getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.title_layout,new ContentFragment())
                            .commit();
                }

生命周期

批注 2019-07-30 152358

通信

Activity 向 Fragment传值

// Activity 端
TitleFragment titleFragment  = new TitleFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("id", UUID.randomUUID().toString());
                    titleFragment.setArguments(bundle);
                    getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.title_layout,titleFragment)
                            .commit();
// Fragment端
if (getArguments() != null){
            textView.setText(getArguments().getString("id"));
        }

Fragment 向 Activity 传值

linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null){
                    listener.onClick();
                }

            }
        });


///////////////


 public interface TitleFragmentClickListener{
        void onClick();
    }

    public void setListener(TitleFragmentClickListener listener) {
        this.listener = listener;
    }

titleFragment.setListener(new TitleFragment.TitleFragmentClickListener() {
                        @Override
                        public void onClick() {
                            Toast.makeText(getApplicationContext(),"click 111",Toast.LENGTH_SHORT).show();
                        }
                    });

Fragment 向 Fragment 传值

getFragmentManager().findFragmentById()

ListFragment