我有Fragment
一个ListView
。当我单击此列表中的某个元素时,我想在 a 中显示单击元素的标题Snackbar
,但出现错误。我该如何解决?
分片方法:
mListViewSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View rowView = view;
TextView tv = (TextView) rowView.findViewById(R.id.song_title);
Song selectedSong = (Song) mListViewSongs.getItemAtPosition(position);
String title = "▶ "+selectedSong.getSongName();
mainActivity.setSelectedSong(title);
}
});
里面使用的方法Activity
:
public void setSelectedSong(String title) {
Snackbar snack = Snackbar.make(coordinatorLayout, title, Snackbar.LENGTH_SHORT);
View viewSnack = snack.getView();
TextView txtv = (TextView) viewSnack.findViewById(android.support.design.R.id.snackbar_text);
txtv.setGravity(Gravity.CENTER_HORIZONTAL);
snack.show();
}
另外,我测试了将文本居中对齐的 Snackbar 方法,但它不起作用,为什么?
日志:
FATAL EXCEPTION: main
Process: com.sebbsoft.app, PID: 2080
Theme: themes:{}
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.ViewGroup.getContext()' on a null object reference
at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
at android.support.design.widget.Snackbar.make(Snackbar.java:215)
at com.sebbsoft.app.PlayActivity.setSelectedSong(PlayActivity.java:354)
at com.sebbsoft.app.Fragments.TracksListFragment$2.onItemClick(TracksListFragment.java:133)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3066)
at android.widget.AbsListView$3.run(AbsListView.java:3903)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)