[英]NullPointerException using Imagebutton in fragment
我在一個片段中使用了一個imagebutton,並嘗試使用圖像按鈕打開抽屜布局。片段和活動都具有該按鈕並且位於相同的位置,所以我在兩個地方都放置了代碼活動代碼可能無法正常工作,因為片段覆蓋了它
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視圖給eclipse中的錯誤,並且不起作用
問題:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.