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。