jk2K's 窝

休息,是为了更好的前行

哈喽, 我是叶萌(@jk2K), 一名来自中国的 PHP / iOS 开发者


Fragment 最佳实践

初始化 Fragment

对于不需要接收参数的Fragment,只需要实现

public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

方法即可

传参给 Fragment

Fragment需要提供一个静态的创建方法, 通常叫做newInstance

public class DemoFragment extends Fragment {
public static DemoFragment newInstance(String someTitle) {
DemoFragment demoFragment = new DemoFragment();
args.putString("someTitle", someTitle);
demoFragment.setArguments(args);
return demoFragment;
}
...
}

你可以这样获取参数

public class DemoFragment extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Get arguments
String someTitle = getArguments().getString("someTitle", "");
}
...
}

你可以这样来调用DemoFragment

DemoFragment.newInstance("测试").show(getSupportFragmentManager(), "DemoFragment");

Activity 与 Fragment 之间的通讯

方法1

Fragment里通过getActivity()来直接调用Activity里面的方法
例如

((MainActivity) getActivity()).doPositiveClick();

方法2

Activity通过实现Fragment里的接口来与Fragment进行交互
例如

第一步

NewsItemFragment定义OnNewsItemSelectedListener接口

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方法

Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onNewsItemSelected(position);
}

第三步

MainActivity里实现OnNewsItemSelectedListener接口

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来控制

参考文档

comments powered by Disqus