Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android design library Snackbar - getting TextView returns Null

I'm trying to get hold of the Snackbar's TextView. This is the code I'm using:

 Snackbar snackbar = Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_LONG);
 View view = snackbar.getView();
 TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);

Running the above always sets tv to null. I'm using design library version 23.0.0 and in the layout resource for the snackbar, I can see the TextView with id snackbar_text. What am I missing?

like image 552
vkislicins Avatar asked Apr 07 '16 11:04

vkislicins


3 Answers

For those who came are having trouble finding an up-to-date answer on this, I'm here to help.

Many examples show the use of this res id:

android.support.design.R.id.snackbar_text

It has since been replaced with:

com.google.android.material.R.id.snackbar_text

Example:

Snackbar snackbar = Snackbar.make( /*however you decide to make it*/ );
View view = snackbar.getView();
TextView tv = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
//make your needed changes...
like image 102
NateLillie Avatar answered Nov 15 '22 18:11

NateLillie


I had the same problem and was able to fix it by not using the id from android.support.design.R.id.snackbar_text.

If you look at the source of the design support library you can see that R.id.snackbar_text is set to:

public static final int snackbar_text = 0x7f0c006b;

If you look at the value of android.support.design.R.id.snackbar_text in your App, you can see that the value is:

public static final int snackbar_text = 0x7f0b006b;

For me, this issue only happens if I use the Design Support Library in a library module.

like image 39
BauerMitFackel Avatar answered Nov 15 '22 19:11

BauerMitFackel


Following code should work:

View containerView = inflater.inflate(R.layout.fragment_foo, container, false); 
Snackbar snackbar = Snackbar.make(containerView, "snackbar text", Snackbar.LENGTH_SHORT); 
View snackbarView = snackbar.getView(); 
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
text.setText("It works"); snackbar.show();
like image 1
Jeffalee Avatar answered Nov 15 '22 17:11

Jeffalee