Kotlin定义静态变量、静态方法
kotlin定义静态变量、方法可以采用伴生对象companion object
的方式。
经典例子,实例化Fragment。
java写法:
public class TestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public TestFragment() {
}
public static TestFragment newInstance(String param1, String param2) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
}
kotlin写法:
class TestFragment : Fragment() {
companion object {
private val ARG_PARAM1 = "param1"
private val ARG_PARAM2 = "param2"
fun newInstance(param1: String, param2: String): TestFragment {
val fragment = TestFragment()
val args = Bundle()
args.putString(ARG_PARAM1, param1)
args.putString(ARG_PARAM2, param2)
fragment.arguments = args
return fragment
}
}
private var mParam1: String? = null
private var mParam2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
mParam1 = arguments!!.getString(ARG_PARAM1)
mParam2 = arguments!!.getString(ARG_PARAM2)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_test, container, false)
}
}