Match parent for width of ImageView in snackbar with custom view in Android is not working

孤人 提交于 2019-12-04 18:53:17

Try following code,

private void showSnackbarAd(View view,Ad ad) {
        final Snackbar snackbar = Snackbar.make(view,"",Snackbar.LENGTH_LONG);
        Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)snackbar.getView();

        layout.setPadding(0, 0, 0, 0);//set padding to 0

        TextView textView = (TextView) layout.findViewById(android.support.design.R.id.snackbar_text);
        textView.setVisibility(View.INVISIBLE);
        View snackView = getLayoutInflater().inflate(R.layout.snack_bar_ad, layout);// use the parent ViewGroup instead of null
        ImageView imageView = (ImageView)snackView.findViewById(R.id.snackbar_ad_image);
        Picasso.with(getBaseContext()).load(ad.getImageUrl()).into(imageView);
        //layout.addView(snackView, 0);
        snackbar.show();
}

You can try this library. This is a wrapper for android default snackbar. https://github.com/ChathuraHettiarachchi/CSnackBar

Snackbar.with(this,null)
    .type(Type.SUCCESS)
    .message("Profile updated successfully!")
    .duration(Duration.SHORT)
    .show();

or you can even use your own view,

View view = getLayoutInflater().inflate(R.layout.custom_view, null);

Snackbar.with(this,null)
        .type(Type.UPDATE)
        .contentView(view, 76)
        .duration(Duration.SHORT)
        .show();

You will have to specify width in xml. So image will fit into that width. match_parent attribute will not set width as no specific size is specified.

Use can also try the below code,

Picasso.with(image.getContext()).load(ad.getImageUrl()).into(new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        image.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {

                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                });

Whenever use a custom view, always avoid using LinearLayout as root element. It screws things up sooooooo oooooooften.

For your problem, try to replace LinearLayout in the xml with RelativeLayout.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!