显示不带CoordinatorLayout的小吃店 [英] Display Snackbar without CoordinatorLayout
问题描述
我已经使用CoordinatorLayout显示了Snackbar,但是在某些布局中我没有使用CoordinatorLayout布局,我想显示小吃栏,但是遇到了问题.
I have Displayed Snackbar using CoordinatorLayout but in some layout i did't used CoordinatorLayout layout and i want to display snackbar but faced problem with it.
我尝试了以下方法来在没有CoordinatorLayout的情况下实现小吃店,但它将显示以下结果.
I have tried following way to achieve snackbar without CoordinatorLayout but it will display following result.
Snackbar.make(getActivity().getWindow().getDecorView().getRootView(), "Testing Snackbar", Snackbar.LENGTH_LONG).show();
使用android 8.0 Oreo进行测试
Test it with android 8.0 Oreo
没有CoordinatorLayout可以实现Snackbar吗?
Is there any way to achieve Snackbar without CoordinatorLayout?
谢谢.
代码
public class FirstFragment extends Fragment {
RelativeLayout rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
Log.e("onCreateView", "onCreateView");
rootView = (RelativeLayout)view.findViewById(R.id.rootView);
setSnackBar(rootView, "Testing with answered");
return view;
}
public static void setSnackBar(View coordinatorLayout, String snackTitle) {
Snackbar snackbar = Snackbar.make(coordinatorLayout, snackTitle, Snackbar.LENGTH_SHORT);
snackbar.show();
View view = snackbar.getView();
TextView txtv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
txtv.setGravity(Gravity.CENTER_HORIZONTAL);
}
}
推荐答案
public static void setSnackBar(View root, String snackTitle) {
Snackbar snackbar = Snackbar.make(root, snackTitle, Snackbar.LENGTH_SHORT);
snackbar.show();
View view = snackbar.getView();
TextView txtv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
txtv.setGravity(Gravity.CENTER_HORIZONTAL);
}
只需调用上述方法并传递任何父级布局,例如LinearLayout
,RelativeLayout
或ScrollView
,即可:
Just call the above method and pass any parent layout such as LinearLayout
, RelativeLayout
or ScrollView
, for example:
setSnackBar(layout,"This is your SnackBar"); //here "layout" is your parentView in a layout
不要忘记使用findViewById()
查找视图.
Do not forget to find your view using findViewById()
.
这篇关于显示不带CoordinatorLayout的小吃店的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!