2017-09-18 39 views
3

我使用CoordinatorLayout顯示Snackbar,但在某些佈局中,我沒有使用CoordinatorLayout佈局,我想顯示快餐欄但面臨問題。沒有CoordinatorLayout的顯示Snackbar

我試過下面的方式來實現小吃棒沒有CoordinatorLayout,但它會顯示以下結果。

Snackbar.make(getActivity().getWindow().getDecorView().getRootView(), "Testing Snackbar", Snackbar.LENGTH_LONG).show(); 

enter image description here

與Android 8.0奧利奧

測試它是否有任何的方式來實現,而不小吃吧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); 
    } 
} 

回答

6
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); 
} 

只需撥打上面的方法,並通過任何父佈局如LinearLayoutRelativeLayoutScrollView,例如:

setSnackBar(layout,"This is your SnackBar"); //here "layout" is your parentView in a layout 

不要忘了找你的看法使用findViewById()

+0

首先感謝我試圖回答 ,但它會給以下錯誤 從給定的觀點沒有找到合適的母體。請提供有效的視圖。 –

+0

@NileshPanchal在我的情況下,它正在爲任何視圖工作,我剛剛把這個代碼放在我的Utils類中,並且調用了這個方法,並且它的工作方式像魅力 –

+0

@NileshPanchal你提供並找到了你父視圖的id? –

4

試試這個簡單的一段代碼..

Snackbar.make(findViewById(android.R.id.content),"Your Text Here",Snackbar.LENGTH_SHORT).show();

+0

我試圖在適配器類中顯示快餐欄,因爲我傳遞給適配器的所有內容都是上下文,所以此功能完美無缺。 – Manny265