java - 创建 fragment View 时崩溃

标签 java android nullpointerexception android-view

我已经在 fragment 内的 ImageButton 上放置了一个用于 Intent Activity 的单击事件。但应用程序崩溃并出现以下错误。

Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

AccountFragment.java

    public class AccountInfoFragment extends Fragment {
    private ArrayList<MyAccountsCard> myAccountsCardData;

    public AccountInfoFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view =  inflater.inflate(R.layout.fragment_account_info, container, false);
        RecyclerView myAccountView=(RecyclerView) view.findViewById(R.id.my_accounts_view);


        myAccountView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL, false));

        initializeData();

        MyAccountsCardAdapter myAccountsCardAdapter= new MyAccountsCardAdapter(myAccountsCardData);
        myAccountView.setAdapter(myAccountsCardAdapter);
        final ImageButton iButtonShare = (ImageButton)view.findViewById(R.id.shareButton);
        iButtonShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getContext().getApplicationContext(),AccountShareActivity.class);
                startActivity(i);
            }
        });

        return view;
    }

    private void initializeData(){
        myAccountsCardData= new ArrayList<>();
        myAccountsCardData.add(new MyAccountsCard("12345678901234","scheme1","current","120000"));
        myAccountsCardData.add(new MyAccountsCard("12345678901234","scheme2","savings","5000"));
    }

}

最佳答案

iButtonShare 对象为空。您确定已将此按钮添加到 xml 布局 R.layout.fragment_account_info 中吗?此布局中的按钮是否具有正确的 id (shareButton)?

关于java - 创建 fragment View 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41424900/

相关文章:

java - XSLT 转换,如果源中不存在则输出元素,如果存在则保持原样

java - 更改android中复选框的大小

android - 如何在android中获取视频缩略图?

mysql - 如何在android模拟器中获取mysql数据库连接

java - 如何修复 Jaspersoft Studio 插件中由 TraceGovernor 引起的 java.lang.NullPointerException?

java - ServletFileUpload 异常

java - Log4j2 JMX : Updating the logging level via jConsole doesn't take effect

java - 对人物相似度算法的建议

java - Java 是否允许和接受 hashCode 和 equals 方法中的异常?

java - Android NullPointerException 在 View 或适配器中或