最近有在学习Android引用开发
平台是:Android stdio
SDK:Android 10、API 29
废话开始了!!!!
为了实现底部导航菜单栏的功能,增加了Fragment。在定义好的Fragment页面中有<Button>控件定义在xml文档中,在定义页面类文件为其实现功能时,发现不能使用findViewById()方法来获取控件。
原来Fragment页面默认继承的是Fragment类,并没有实例化页面为Activity。而findViewById()方法是Activity实例独有的获取控件的方法。
解决方法:
通过getActivity()方法。以下是getActivity()的函数定义:可知getActivity()方法返回的是一个FragmentActivity对象。
/**
* Return the {@link FragmentActivity} this fragment is currently associated with.
* May return {@code null} if the fragment is associated with a {@link Context}
* instead.
*
* @see #requireActivity()
*/
@Nullable
final public FragmentActivity getActivity() {
return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}
于是我试过使用getActivity()方法来
结果报错来了:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myschool10, PID: 14418
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
原来是在onCreateView()方法中不能使用setOnClickListener()的事件监听
必须换在onActivityCreated()方法中使用
完整版代码:
public class PushFragment extends Fragment {
private Button addphoto;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.push_fragment,container,false);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button button =getActivity().findViewById(R.id.click_to_push);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("success");
}
});
}
}