Android - 如何显示包含从片段中获取的字符串的快餐栏
Posted
技术标签:
【中文标题】Android - 如何显示包含从片段中获取的字符串的快餐栏【英文标题】:Android - how to show a snackbar containing a string taken from a fragment 【发布时间】:2016-09-07 13:29:04 【问题描述】:我有一个Fragment
和一个ListView
。当我单击此列表中的某个元素时,我想在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)
【问题讨论】:
【参考方案1】:您可以直接在片段中显示Snackbar
,而不是调用活动的方法。
直接在onItemClick()
中尝试这个你想显示Snackbar
的地方-
Snackbar snack = Snackbar.make(android.R.id.content, 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”中将文本设置为“CENTER_HORIZONTAL”,如您所见,我在代码中编写了它,但它不起作用,我该如何解决?以上是关于Android - 如何显示包含从片段中获取的字符串的快餐栏的主要内容,如果未能解决你的问题,请参考以下文章