2016-04-07 4 views
0

Я пытаюсь показать пользовательские закусочной, как в этом примере:Пользовательские Snackbar не работает должным образом

how to customize snackBar's layout?

Это мой собственный код для создания закусочной:

protected void showSnackBar(View view) { 

    Snackbar snackbar = Snackbar.make(view, "", Snackbar.LENGTH_INDEFINITE); 
    Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView(); 
    TextView textView = (TextView) layout.findViewById(android.support.design.R.id.snackbar_text); 
    textView.setVisibility(View.INVISIBLE); 

    LayoutInflater inflater = LayoutInflater.from(this); 

    View snackView = inflater.inflate(R.layout.custom_snackbar, null); 

    layout.addView(snackView, 0); 

    ViewGroup group = (ViewGroup) snackbar.getView(); 
    group.setBackgroundColor(ContextCompat.getColor(this, R.color.green_wasabi)); 

    snackbar.show(); 

} 

Моя цель состоит в том, чтобы метод в моей базовой деятельности вызывал любую другую деятельность.

Но моя проблема в том, когда я показываю закусочной, что показано под клавиатурой:

Example

Кроме того, он не показывает весь вид макета:

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/relativelayout_sync_schedule_runs" 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:padding="10dp" 
android:background="@color/green_wasabi" 
android:layout_alignParentBottom="true" 
android:layout_gravity="center_horizontal|bottom"> 

<ProgressBar 
    android:id="@+id/progressbar_infinite" 
    android:layout_width="30dp" 
    android:layout_height="30dp" 
    style="@android:style/Widget.Material.ProgressBar.Small" 
    android:layout_centerVertical="true" 
    android:layout_marginRight="15dp" 
    android:layout_toLeftOf="@+id/textview_sync_runs" 
    android:layout_toStartOf="@+id/textview_sync_runs" /> 


<com.runator.ui.widget.text.CustomTextView 
    android:id="@+id/textview_sync_runs" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/import_runs" 
    android:textColor="@color/black_midnight" 
    style="@style/texts.medium_medium_big" 
    app:font_type="bold" 
    android:gravity="center" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true"/> 

Если у кого-то есть предложения, я буду рад его услышать.

Заранее спасибо.

+0

Вы можете поделиться своим файлом layout.xml, который принадлежит к BaseActivity? –

+0

My BaseActivity не имеет макета – dpulgarin

+0

Кажется, вы используете полупрозрачную навигационную панель (либо настроенную в стилях/тему, либо программно). Вот почему ваш макет простирается до полной высоты дисплея, а ваша закусочная добавлена ​​внизу. Вы можете попробовать добавить android: fitsSystemWindows = "true" к вашему родительскому элементу в вашем макете, но тогда контент не будет растягиваться за панель навигации. Если вы все еще хотите, чтобы контент растянулся за ним, но у вас есть snacker сверху, вам придется программно изменить свое положение, когда оно будет показано. – peshkira

ответ

2

Прежде всего, вам не нужно устанавливать цвет фона программно, как вы уже делаете, что в XML-файлы, так что удалить эти строки

ViewGroup group = (ViewGroup) snackbar.getView(); 
group.setBackgroundColor(ContextCompat.getColor(this, R.color.green_wasabi)); 

Во-вторых, попробуйте с переходом Coordinator Layout из активность как аргумент, а не Linear/Relative Layout, то есть добавить компоновку координатора в качестве родительского макета в действие и передать его.

Проверьте рамки расположения координатора в представлении xml. Он не должен расширять границы деятельности.

+0

Работает отлично! Благодаря!! – dpulgarin

+0

Нет проблем :). – Yashasvi

2

Можете ли вы попробовать этот код для добавления Snackbar в свою Baseactivity.

Snackbar snackbar = Snackbar.make(rootView, text, Snackbar.LENGTH_LONG); 
View snackBarView = snackbar.getView(); 
snackBarView.setBackgroundColor(this.mContext.getResources().getColor(R.color.pepapp_bright_red)); 
snackbar.show(); 
+0

Проведите ту же проблему – dpulgarin

1

Код ниже работает так же, как и Snackbar, но полный пользовательских (UI, анимация, действия ...) компонентов.

public class CustomSnackBar extends 
     BaseTransientBottomBar<CustomSnackBar> { 

    /** 
    * Time duration till the snackbar is visible to user 
    */ 
    public static final int DURATION_SEC_2 = 2000; 

    /** 
    * Constructor for the transient bottom bar. 
    * 
    * @param parent The parent for this transient bottom bar. 
    * @param content The content view for this transient bottom bar. 
    * @param callback The content view callback for this transient bottom bar. 
    */ 
    private CustomSnackBar(ViewGroup parent, View content, ContentViewCallback callback) { 
     super(parent, content, callback); 
    } 

    public static CustomSnackBar make(@NonNull ViewGroup parent, @Duration int duration) { 
     final LayoutInflater inflater = LayoutInflater.from(parent.getContext()); 
     final View content = inflater.inflate(R.layout.snackbar_view, parent, false); 
     final ContentViewCallback viewCallback = new ContentViewCallback(content); 
     final CustomSnackBar customSnackbar = new CustomSnackBar(parent, content, viewCallback); 
     customSnackbar.setDuration(duration); 
     return customSnackbar; 
    } 

    public CustomSnackBar setText(CharSequence text) { 
     TextView textView = (TextView) getView().findViewById(R.id.snackbar_text); 
     textView.setText(text); 
     return this; 
    } 

    public CustomSnackBar setAction(CharSequence text, final View.OnClickListener listener) { 
     Button actionView = (Button) getView().findViewById(R.id.snackbar_action); 
     actionView.setText(text); 
     actionView.setVisibility(View.VISIBLE); 
     actionView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       listener.onClick(view); 
       // Now dismiss the Snackbar 
       dismiss(); 
      } 
     }); 
     return this; 
    } 

    private static class ContentViewCallback implements BaseTransientBottomBar.ContentViewCallback { 

     private View content; 

     public ContentViewCallback(View content) { 
      this.content = content; 
     } 

     @Override 
     public void animateContentIn(int delay, int duration) { 
      ViewCompat.setScaleY(content, 0f); 
      ViewCompat.animate(content).scaleY(1f).setDuration(duration).setStartDelay(delay); 
     } 

     @Override 
     public void animateContentOut(int delay, int duration) { 
      ViewCompat.setScaleY(content, 1f); 
      ViewCompat.animate(content).scaleY(0f).setDuration(duration).setStartDelay(delay); 
     } 
    } 
}