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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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)
}
}
---------------------
作者:清风徐来qfxl
来源:CSDN
原文:https://blog.csdn.net/xuyonghong1122/article/details/80268981
版权声明:本文为博主原创文章,转载请附上博文链接!
原文地址:https://www.cnblogs.com/weizhxa/p/9982532.html