Пользовательская закусочная не работает должным образом

Я пытаюсь показать пользовательскую закусочную, как в этом примере:

как настроить макет закусочной?

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

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();

}

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

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

Пример

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

<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"/>

If anyone has any suggestions I will be happy to hear it.

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


person dpulgarin    schedule 07.04.2016    source источник
comment
Можете ли вы поделиться своим файлом layout.xml, который принадлежит BaseActivity?   -  person Olkunmustafa    schedule 07.04.2016
comment
У моей BaseActivity нет макета   -  person dpulgarin    schedule 07.04.2016
comment
Кажется, вы используете полупрозрачную панель навигации (установленную в ваших стилях/теме или программно). Вот почему ваш макет растягивается на всю высоту дисплея, а ваша закусочная добавляется внизу. Вы можете попробовать добавить android:fitsSystemWindows=true к своему родительскому элементу в макете, но тогда содержимое не будет растягиваться за панелью навигации. Если вы по-прежнему хотите, чтобы содержимое растягивалось за ним, а закуска была сверху, вам придется программно изменить его положение при его отображении.   -  person peshkira    schedule 07.04.2016


Ответы (3)


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

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

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

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

person Yash    schedule 07.04.2016
comment
Работает отлично! Спасибо!! - person dpulgarin; 07.04.2016

Можете ли вы попробовать этот код для добавления 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();
person Olkunmustafa    schedule 07.04.2016
comment
Проведите ту же проблему - person dpulgarin; 07.04.2016

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

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);
        }
    }
}
person Sandipkumar Savani    schedule 16.01.2018