Fragment 最佳实践
初始化 Fragment
对于不需要接收参数的Fragment
,只需要实现
1
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
方法即可
传参给 Fragment
Fragment
需要提供一个静态的创建方法, 通常叫做newInstance
1
2
3
4
5
6
7
8
9
10
public class DemoFragment extends Fragment {
public static DemoFragment newInstance(String someTitle) {
DemoFragment demoFragment = new DemoFragment();
args.putString("someTitle", someTitle);
demoFragment.setArguments(args);
return demoFragment;
}
...
}
你可以这样获取参数
1
2
3
4
5
6
7
8
9
10
11
public class DemoFragment extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Get arguments
String someTitle = getArguments().getString("someTitle", "");
}
...
}
你可以这样来调用DemoFragment
1
DemoFragment.newInstance("测试").show(getSupportFragmentManager(), "DemoFragment");
Activity 与 Fragment 之间的通讯
方法1
在Fragment
里通过getActivity()
来直接调用Activity
里面的方法 例如
1
((MainActivity) getActivity()).doPositiveClick();
方法2
Activity
通过实现Fragment
里的接口来与Fragment
进行交互 例如
第一步
NewsItemFragment
定义OnNewsItemSelectedListener
接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class NewsItemFragment extends Fragment {
OnNewsItemSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnNewsItemSelectedListener {
public void onNewsItemSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnNewsItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnNewsItemSelectedListener");
}
}
...
}
第二步
NewsItemFragment
调用onNewsItemSelected
方法
1
2
3
4
5
Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onNewsItemSelected(position);
}
第三步
MainActivity
里实现OnNewsItemSelectedListener
接口
1
2
3
4
5
6
7
8
9
10
11
12
public class MainActivity extends AppCompatActivity implements NewsItemFragment.OnNewsItemSelectedListener
{
...
@Override
public void onNewsItemSelected(int position)
{
//Do something with the position value passed back
Toast.makeText(activity, "Clicked "+ position, Toast.LENGTH_LONG).show();
}
}
方法2比方法1更复杂,但是在某些情况下可能必须要这样实现
注意
Fragment
之间不可直接进行通讯,需通过Activity
来控制
参考文档
本文由作者按照 CC BY 4.0 进行授权
Comments powered by Disqus.