Fragment嵌套Fragment

Fragment嵌套Fragment是很常用的,会得到一个类似千层面的东西?这样使用是为了减少Activity的使用。

注意事项:

1. 获取控件及设置控件要在 Fragment的onCreateView()方法

//修改前
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_main, container, false);
}

//修改后
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_main, container, false);

    // View v= view.findViewById(R.id.~);
    // v.setXXX(~);

    return view;
}

2. FragmentManager

FragmentManager需要在Activity中使用getSupportFragmentManager()方法获取,无法在Fragment中获取;可以在Activity中获取后传入Fragment,可用设置Fragment构造函数参数等方法。

3. getSystemService

如果Fragment中需要使用到各种Manager,如InputMethodManager等,可在Activity中使用getSystemService()方法获取Manager后并传入,因为Fragment无法使用getSystemService()方法。

4. 对Fragment中控件操作

可以通过创建的Fragment对象操作其中的控件,操作控件时请确保控件不为Null

更推荐使用handler在创建Fragment中控件的线程中对控件进行操作。

即在创建控件时创建用于修改控件的Handler,在其他线程中调用Handler修改控件。

class MyFragment extends Fragment {

    public TextView textView;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_main, container, false);
    
        textView=view.findViewById(R.id.textView);
        textView.setText(" default_text ");

        return view;
    }

    ... ...
}
public class MainActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        
        //创建碎片对象
        MyFragment myFragment=new MyFragment();

        //... ...碎片事务... ...

        //操作控件(请确保此时控件不为Null)
        myFragment.textView.setText(" new_text ");

    }
    ... ...
}

5. Context与Activity

在Fragment的方法中可使用getContext()方法获取Context,可使用getActivity()方法获取Activity。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

在下嗷呜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值