我正在片段中使用图像按钮,并尝试使用图像按钮打开drawerlayout nah片段和活动都有这个按钮,并在相同的地方,所以我已经在两个地方放置代码 活动代码可能不起作用,因为片段覆盖它
public class MainFragment extends Fragment {
private ImageButton mImageButton;
public MainFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_main, container,
false);
mImageButton = (ImageButton) getView().findViewById(R.id.qpaper_menu_fragmain);
mImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MyActivity)getActivity()).openDrawer();
}
});
return view;
}
}
xml中的imagebutton
<ImageButton
android:id="@+id/qpaper_menu_fragmain"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@drawable/menu_button_blue"
android:contentDescription="@string/description" />
编辑:抱歉,上面说的是视图 我用GetView得到NullPointerException 视图在日食中发出错误并且无法正常工作
答案 0 :(得分:2)
<强>问题:强>
View().findViewById(R.id.qpaper_menu_fragmain);
您无法从类中查找/引用视图的ID,您需要从已经完成的视图中查找/引用它。
<强>溶液强>
View view = inflater.inflate(R.layout.fragment_main, container,false);
mImageButton = (ImageButton) view.findViewById(R.id.qpaper_menu_fragmain);