为什么要在Android应用的单个Java文件中放置多个接口?

时间:2018-02-14 02:27:46

标签: java android design-patterns

我已经在Android应用程序上工作了几个月。在我读过的许多更复杂的开源程序中,我不断遇到多个接口或一个嵌入式接口的类在一个文件中。甚至Android Studio都会以这种方式生成片段。

现在,我是一个古老的老傻瓜。我从1.1版开始就用Java编程。我一直被教导将类,接口和枚举器放在单独的文件中。相关项目放在同一个包中。

是否有理由将相关接口填充到单个文件中而不是遵循此最佳做法?

给出的例子:

public class BlankFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public BlankFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment BlankFragment.
 */
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
    BlankFragment fragment = new BlankFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}
... more code ...
/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

1 个答案:

答案 0 :(得分:2)

在另一个类中定义接口为该接口提供方向和上下文。独立的OnCheckedChangeListener并没有告诉您如何将该界面用作CompoundButton.OnCheckedChangeListener vs RadioGroup.OnCheckedChangeListener。它还允许这些接口中定义的方法不同,而不会让开发人员猜测要导入哪一个来获得他们需要的东西。