代码用于在用户点击按钮时打开webview,但我收到错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at info.teammumu.cougarcardapp.SocialMediaFragment.onCreateView(SocialMediaFragment.java:28)
代码:
public class SocialMediaFragment extends Fragment {
public ImageButton fbbutton;
public ImageButton twbutton;
public ImageButton igbutton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_socialmedia, container, false);
fbbutton = (ImageButton) getActivity().findViewById(R.id.fbbutton);
twbutton = (ImageButton) getActivity().findViewById(R.id.twbutton);
igbutton = (ImageButton) getActivity().findViewById(R.id.igbutton);
fbbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/universityofhouston"));
startActivity(browserIntent);
}
});
twbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("website"));
startActivity(browserIntent);
}});
igbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("website"));
startActivity(browserIntent);
}});
return rootView;
}}
之前我问过这样的问题,但是从来没有回答过,或者我也不理解...... How to open a webview from imagebutton? 感谢任何可以提供帮助的人!过去几天我一直试图解决这个问题但没有成功。它崩溃了,我无法打开标签。
答案 0 :(得分:1)
使用rootView
代替getActivity()
访问从onCreateView
返回的Fragment布局中的视图:
fbbutton = (ImageButton) rootView.findViewById(R.id.fbbutton);
twbutton = (ImageButton) rootView.findViewById(R.id.twbutton);
.....
因为getActivity
返回Activity的上下文,其中添加了当前片段,因此调用getActivity().findViewById(<ID>)
意味着从Activity Layout而不是Fragment访问视图。
答案 1 :(得分:0)
如果你在同一个视图中有按钮,那么你应该更改这些行:
fbbutton = (ImageButton) getActivity().findViewById(R.id.fbbutton);
twbutton = (ImageButton) getActivity().findViewById(R.id.twbutton);
igbutton = (ImageButton) getActivity().findViewById(R.id.igbutton);
就像:
fbbutton = (ImageButton) rootView.findViewById(R.id.fbbutton);
twbutton = (ImageButton) rootView.findViewById(R.id.twbutton);
igbutton = (ImageButton) rootView.findViewById(R.id.igbutton);