我已经在 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/