"Fragment"-Android面试必问"精华技能点"汇总

Fragment技能点汇总总结:
目录:

一.Fragment跟Activity如何传值?

一.getActivity()

  • 1.从Fragment获取Ativity的信息
  • 2.就可以调用Ativity的方法了

二.setArguments(Bundle)

  • 在Ativity获取Fragment的实例和方法
  • 过程和代码如下:

    • 1.获取管理者

      FragmentManager fragmentManager = getFragmentManager();
      
    • 2.找到fragment

      Fragment fragment = fragmentManager.findFragmentByTag(tag);
      Fragment fragment = fragmentManager.findFragmentById(id);
      
    • 3.一般直接管理对象.获取事物(替换布局,frgmentXX).提交.

  • 可调用fragment的setArguments(bundle)把数据绑定到Fragment中.
  • 为什么官方推荐 Fragment.setArguments(Bundle bundle)这种方式来传递参数,而不推荐通过构造方法直接来传递参数呢? 请看以下两个例子:

案例一:通过fragment构造传给Activity

public class FramentTestActivity extends ActionBarActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
      getSupportFragmentManager().beginTransaction()
          .add(R.id.container, new TestFragment("param")).commit();
    }

  }

  public static class TestFragment extends Fragment {

    private String mArg = "non-param";

    public TestFragment() {
      Log.i("INFO", "TestFragment non-parameter constructor");
    }

    public TestFragment(String arg){
      mArg = arg;
      Log.i("INFO", "TestFragment construct with parameter");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
      View rootView = inflater.inflate(R.layout.fragment_main, container,
          false);
      TextView tv = (TextView) rootView.findViewById(R.id.tv);
      tv.setText(mArg);
      return rootView;
    }
  }

}

结果: 能正常显示
当横屏后:得到的值为null


案例二:换成setArguments(bundle)传递值

public class FramentTest2Activity extends ActionBarActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
             setContentView(R.layout. activity_main);

  if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
         .add(R.id. container, TestFragment.newInstance("param")).commit();
             }

       }

        public static class TestFragment extends Fragment {

  private static final String ARG = "arg";

  public TestFragment() {
        Log. i("INFO", "TestFragment non-parameter constructor" );
             }

  public static Fragment newInstance(String arg){
        TestFragment fragment = new TestFragment();
        Bundle bundle = new Bundle();
        bundle.putString( ARG, arg);
        fragment.setArguments(bundle);
         return fragment;
             }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
               Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout. fragment_main, container,
          false);
        TextView tv = (TextView) rootView.findViewById(R.id. tv);
        tv.setText(getArguments().getString( ARG));
         return rootView;
             }
       }

}

不论横屏还是竖屏都会得到值


二.描述Fragment的生命周期

一.生命周期图:

这里写图片描述

二.需求

  • 1.屏幕分左右边,左边2/5是点击列表,右边是:上输入框,下文本框
  • 2.最后一个内容fragment,多了个点击按钮.并能获取Activity里的输入框信息.
  • 3.效果图如下图1,2,3
    这里写图片描述

三.代码:

布局:
activity_main.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="horizontal"
    >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:background="#22ff0000"
        android:orientation="vertical">

        <Button
            android:id="@+id/bt_news"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="新闻"/>

        <Button
            android:id="@+id/bt_fun"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="娱乐"/>

        <TextView
            android:id="@+id/tv_sport"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#22000000"
            android:gravity="center"
            android:text="体育"/>


    </LinearLayout>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="0dp"
    android:layout_weight="5"

    android:layout_height="match_parent">
    <EditText

        android:id="@+id/et_info"
        android:layout_width="match_parent"
        android:hint="请输入内容"
        android:layout_height="wrap_content"/>
    <FrameLayout
        android:id="@+id/fl_content"
        android:background="#2200ff00"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</LinearLayout>

</LinearLayout>

fragment_fun.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:orientation="vertical"
              android:layout_height="match_parent">
    <TextView
        android:background="#33ff00f7"
        android:gravity="center"
        android:text="我是娱乐"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

fragment_news.xml

android:background="#330000ff"
android:text="我是新闻"

fragment_sport.xml

<Button
    android:onClick="getInfo"
    android:id="@+id/bt_getInfo"
    android:text="获取输入框内容"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
<Button
    android:onClick="goFun"
    android:id="@+id/bt_goFun"
    android:text="跳到Fun板块"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
<TextView
    android:gravity="center"
    android:text="我是运动"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Java代码:
(分类写)
这里写图片描述


Fragment_fun.java

public class Fragment_fun extends Fragment {
    //1.固定
    @Override
    public void onAttach(Context context) {
        Log.d("abce", "onAttach");
        super.onAttach(context);
    }
    //2.创建
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d("abce", "onCreate");



        super.onCreate(savedInstanceState);
    }
    //3.创建View
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("abce", "onCreateView");
        //填充布局进来
        return inflater.inflate(R.layout.fragment_fun,null);
    }
    //4.创建活动界面
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.d("abce", "onActivityCreated");

        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        Log.d("abce", "onDestroyView");

        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        Log.d("abce", "onDestroy");

        super.onDestroy();
    }

    @Override
    public void onDetach() {
        Log.d("abce", "onDetach");

        super.onDetach();
    }
}

Fragment_news.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.d("abce", "onCreateView");
    //填充布局
    return inflater.inflate(R.layout.fragment_news,null);
}

Fragment_sport.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.d("abce", "onCreateView");
    View view =inflater.inflate(R.layout.fragment_sport,null);
    mBt_getInfo = (Button) view.findViewById(R.id.bt_getInfo);
    mBt_getInfo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //通过getActivity()方法获取到绑定的Activity对象
            EditText et = (EditText) getActivity().findViewById(R.id.et_info);
            String str = et.getText().toString().trim();
            if (TextUtils.isEmpty(str)) {
                Toast.makeText(getActivity(), "null", Toast.LENGTH_SHORT).show();
                return;
            }
            Toast.makeText(getActivity(),"获取到的信息是"+str,Toast.LENGTH_SHORT).show();
        }
    });
    Button goA = (Button) view.findViewById(R.id.bt_goFun);
    goA.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().beginTransaction().replace(R.id.fl_content, new Fragment_fun()).commit();
        }
    });
    return view;
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mBt_news;
    private Button mBt_fun;
    private TextView mTv_sport;
    private FragmentTransaction mFt;
    private FragmentManager mFm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initView();
    }

    private void init() {
        // 获取管理对象
        mFm = getFragmentManager();
        // 获取事物
        mFt = mFm.beginTransaction();
        // 开始的时候马上替换,帧布局先放new模块;
        mFt.replace(R.id.fl_content, new Fragment_news());
        // 提交
        mFt.commit();

    }

    private void initView() {
        mBt_news = (Button) findViewById(R.id.bt_news);
        mBt_fun = (Button) findViewById(R.id.bt_fun);
        mTv_sport = (TextView) findViewById(R.id.tv_sport);

        mBt_news.setOnClickListener(this);
        mBt_fun.setOnClickListener(this);
        mTv_sport.setOnClickListener(this);
    }

    /**
     * 各个板块的点击事件: 每点击一个,创建一个: 1.管理 2.事务 3.事务替换内容 4.提交
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.bt_news:
            getFragmentManager().beginTransaction().replace(R.id.fl_content, new Fragment_news()).commit();
            break;
        case R.id.bt_fun:
            getFragmentManager().beginTransaction().replace(R.id.fl_content, new Fragment_fun()).commit();
            break;
        case R.id.tv_sport:
            getFragmentManager().beginTransaction().replace(R.id.fl_content, new Fragment_sport()).commit();
            break;
        }
    }
}

三.Fragment的replace和add方法的区别

  • 严格意义上讲不是fragment的方法,而是管理者的方法
  • 常用:比如RadioGroup切换Fragment(每个Fragment都是一个独立的功能模块)

两者比较和注意点:

  • 1.add的时候可以把Fragment 一层层添加到FrameLayout上面,而replace是删掉其他并替换
  • 2.一个FrameLayout只能添加一个Fragment种类,多次添加会报异常,replace则随便替换
    • 替换(上一个fragment会->destroyView和destroy,新的Fragmetnon:三个Create(crete+view+activity)->onStart->onResume)
  • 3.因FrameLayout容器对每个Fragment只能添加一次,所以到达到效果可用fragment的hide和show方法结合.

四.Fragment如何实现类似Activity的压栈和出栈效果?

  • 内部维持的是双向链表结构
  • 该结构可记录我们每次的add和replace我们的Fragment;
  • 当我们点击back按钮会自动帮我们实现退栈按钮
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值