我想爲getView()中的Textview設置OnClickListener - 擴展ArrayAdapter的類的方法。但是,我只能cllick前三個項目,他們後我得到一個NullPointerException。爲什麼?在ArrayAdapter中設置OnClickListener <>
驗證碼:
content = (TextView) view.findViewById(R.id.list_layout);
content.setText(currentLayout.getContent());
public View getView(final int position, @Nullable final View convertView, @NonNull ViewGroup parent) {
currentLayout = getItem(position);
View view = convertView;
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.rowlayout, parent, false);
}
content = (TextView) view.findViewById(R.id.list_layout);
content.setText(currentLayout.getContent());
number = view.findViewById(R.id.number);
layout = view.findViewById(R.id.layout);
content.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
convertView.setBackgroundColor(Color.YELLOW);
}
});
number.setText("1");
return view;
}
的崩潰reprt:
--------- beginning of crash
08-10 15:18:45.591 3845-3845/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.philipp.einkaufsliste110, PID: 3845
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
at com.example.philipp.einkaufsliste110.Adapter.CustomAdapter$1.onClick(CustomAdapter.java:63)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
08-10 15:18:45.592 1651-2151/system_process W/ActivityManager: Force finishing activity com.example.philipp.einkaufsliste110/.MainActivity
08-10 15:18:45.606 1305-3578/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
[ 08-10 15:18:45.627 1651: 4136 D/ ]
HostConnection::get() New Host Connection established 0x8e578440, tid 4136
[ 08-10 15:18:45.628 1651: 4136 W/ ]
Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1
顯示堆棧跟蹤 –
可以粘貼異常 – Swati
異常粘貼到更好的幫助。 –