I build Snackbar by this code:
Snackbar sb = Snackbar.make(drawer, "message", Snackbar.LENGTH_LONG)
.setAction("action", new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
Now I want to change the typeface of message and action button but can't find any solution, How to do that?
You can set TypeFace by getting view from Snack bar
TextView tv = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_text);
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/font_file.ttf");
tv.setTypeface(font);
For AndroidX, use resource ID com.google.android.material.R.id.snackbar_text
Styling Both the Snackbar Text and Action
You can use the same method to style both the snackbar_text and snackbar_action.
Once you've created a snackbar, you can use the following to get the Views associated with the text and the action and then apply whatever adjustments to the view.
Snackbar snackbar = Snackbar.make( ... ) // Create the Snackbar however you like.
TextView snackbarActionTextView = (TextView) snackbar.getView().findViewById( android.support.design.R.id.snackbar_action );
snackbarActionTextView.setTextSize( 20 );
snackbarActionTextView.setTypeface(snackbarActionTextView.getTypeface(), Typeface.BOLD);
TextView snackbarTextView = (TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
snackbarTextView.setTextSize( 16 );
snackbarTextView.setMaxLines( 3 );
In my example, I've set the Action to be font size 20 and Bold, and the Text to be size 16 and allow up to 3 lines.
For AndroidX
android.support.design.R.id.snackbar_text won't be available.
Use com.google.android.material.R.id.snackbar_textinstead.
If you are using kotlin, then I prefer you to use extension function:
fun Snackbar.changeFont()
{
val tv = view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
val font = Typeface.createFromAsset(context.assets, "your_font.ttf")
tv.typeface = font
}
and call it like:
mSnakeBar.changeFont()
In addition to this answer: now package to find snackbar's textview by id is
val snackText = snackView.findViewById<TextView>(
com.google.android.material.R.id.snackbar_text)
Get the snack bar view and apply customization
TextView tv = (TextView) sb.getView().findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);
tv.setTypeface(Typeface.createFromAsset(
getAssets(),
"fonts/ur_file.ttf"));
Or this
SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Add ");
int boldStart = snackbarText.length();
snackbarText.append("bold color");
snackbarText.setSpan(new ForegroundColorSpan(0xFFFF0000), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarText.append(" to Snackbar text");
Snackbar.make(view, snackbarText, Snackbar.LENGTH_LONG).show();
Or you can give a look at this and this.
Thank you.
For those who are still reading this 7 years later, you can change the text appearance of the snackbar for the whole app by overriding its theme parent in your themes.xml file.
<style name="Theme.App" parent="Theme.MaterialComponents.*">
...
<item name="snackbarTextViewStyle">#style/Widget.App.SnackbarTextView</item>
</style>
<style name="Widget.App.SnackbarTextView" parent="Widget.MaterialComponents.Snackbar.TextView">
<item name="android:textAppearance">#style/your_snackbar_text_style</item>
</style>
And then in your styles.xml file insert the your_snackbar_text_style style there
<style name="your_snackbar_text_style">
<item name="android:fontFamily">#font/your_font</item>
</style>
Starting from Support Library 26, fonts can be used as resources.
val mainTextView = view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
val font = ResourcesCompat.getFont(applicationContext, R.font.your_font)
mainTextView.typeface = font
Get assets
AssetManager assets = context.getAssets();
Get Typeface
Typeface typeface = Typeface.createFromAsset(assets,PATH OF .TTF FILE);
Path: font/robotoregular.ttf (if .ttf file is stored in assets/font path)
if you want to change the font of Action Button and textview use this code :
Snackbar.make(this,message,Snackbar.LENGTH_LONG).also {snackbar ->
snackbar.setAction("ok"){
snackbar.dismiss()
}
val actionButton = snackbar.view.findViewById(com.google.android.material.R.id.snackbar_action) as Button
val textview = snackbar.view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
val font = Typeface.createFromAsset(context.assets, "fonts/your_custom_font")
actionButton.typeface = font
textview.typeface = font
ViewCompat.setLayoutDirection(snackbar.view,ViewCompat.LAYOUT_DIRECTION_RTL)
}.show()
For every one that crashes when calling createFromAsset() you can use
Font font = ResourcesCompat.getFont(getApplicationContext(), R.font.your_font);
Related
Code
Button mButton1;
int mDefaultColor1;
SharedPreferences mSharedPreferences1;
SharedPreferences.Editor editor1;
mButton1 = (Button)findViewById(R.id.buttontextfontsent);
mSharedPreferences1 = PreferenceManager.getDefaultSharedPreferences(this);
mDefaultColor1 = mSharedPreferences1.getInt("Default_Color1",ContextCompat.getColor(CustomizeFont.this,R.color.white));
mButton1.setBackgroundColor(mDefaultColor1);
After Picking Color
editor2 = PreferenceManager.getDefaultSharedPreferences(CustomizeColor.this).edit();
editor2.putInt("Default_Color2", color);
editor2.apply();
}
This is what I used to let the user change the color of a button... I want to do the same for font... but having a hard time... can anyone help me out? I want to use sharedpreferences for this.
Do in same manner how you have done for color, you just need to save font as string.
Saving font in Preference
editor.putString("font","selected_font")
getting back from Preference
String fontName = editor.getString("font","default_font");
// make sure fontName is available under assets->fonts
Typeface typeface = Typeface.createFromAsset(context.getAssets(), String.format("fonts/%s.ttf", name));
// Preferred way
Typeface typeface = Typefaces.get(getContext(), name));
Apply typeface to your view
button.setTypeface(typeface);
Here is the optimization part, to avoid the Typeface creation all the time as it is expensive.
class Typefaces {
private static final Hashtable<String, Typeface> FONT_CACHE = new Hashtable<>();
public static Typeface get(Context context, String name) {
if (!FONT_CACHE.containsKey(name)) {
Typeface typeface = Typeface.createFromAsset(context.getAssets(), String.format("fonts/%s.ttf", name));
FONT_CACHE.put(name, typeface);
}
return FONT_CACHE.get(name);
}
}
Make a folder named "Assets" in "src". Copy a font(.ttf) file to Assets folder and use:
Button button=(Button) findViewById(R.id.enter);
Typeface type=Typeface.createFromAsset(getAssets(), "arial.ttf");
button.setTypeface(type);
How can I set a programmatically created checkbox's text to be aligned on the left instead of right side of the checkbox. Below is a code snippet:
Checkbox check1 = new Checkbox(getApplicationContext());
check1.setLayoutParams(new ActionBar.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
check1.setId(fieldNo);
check1.setTextColor(Color.BLACK);
check1.setGravity(Gravity.RIGHT);
check1.setText(formField.get(fieldNo));
The above code resulted in the text shown on the right of the checkbox.
Here is a screenshot :
How can I have the text on the left of the checkbox?
You need to change the following
check1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
In this line you were using ActionBar params and then LinearLayoutCompat params. Try to stick to 1 category and in custom views like checkbox just LinearLayout would do.
UPDATE 1:
You should use CheckedTextView. I have used standard android drawable for that but you can also use your custom Check box design as well.
So your overall code would look like -
final CheckedTextView check1 = new CheckedTextView(getApplicationContext());
check1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
check1.setId(fieldNo);
check1.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
check1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (check1.isChecked()){
check1.setChecked(false);
check1.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
}else{
check1.setChecked(true);
check1.setCheckMarkDrawable(android.R.drawable.checkbox_on_background);
}
}
});
check1.setTextColor(Color.BLACK);
check1.setGravity(Gravity.LEFT);
check1.setText(formField.get(fieldNo));
I have a Snackbar in need to set its height or set height to wrap content. Is there any way?
Snackbar snack = Snackbar.make(findViewById(R.id.activity_container), "Message", Snackbar.LENGTH_SHORT);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
view.setBackgroundColor(Color.RED);
tv.setTextColor(Color.WHITE);
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
We are going to provide multiple answers. First a statement or two! You can set the height and width of a Snackbar but it is messy and time consuming period.
One realization about a Snackbar widget is most tutorials do not talk about styling. The opinion is they should be just the size that the widget gives you NOT MY VIEW. So we have noticed that the text size and number of max lines plays a BIG roll is the size of a well styled Snackbar. So design your Snackbar and style away
OK how to implement the mess Suggestion DO NOT DO THIS declare this variable where you would declare any other variable in your Activity
RelativeLayout rl;
Then when you need to increase the size of your RelativeLayout that is in your XML file but is not the root Layout in this case use this code
rl = (RelativeLayout) findViewById(R.id.svRL);
rl.getLayoutParams().height = 1480;
When you get done with this increased size which can mess with the size of other object in the root Layout you might want to set the size of the root Layout back to what it was. In this case the root Layout was set to layout height 615dp we are working with a Nexus 7 Tablet. If you have not noticed this yet here is the MESS part that 1480 is in units of pixels and you need it in dp. I am sure the conversion can be made just do not ask me. So here is the set back line of code
rl.getLayoutParams().height = 1230;
Now for a easy way to design and style two types of Snackbar's one with an Action button and one with out. First you need a CoordinatorLayout in what ever Activity corresponding XML file that looks like this Note it has an id
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coorSB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" >
<!-- android.support.design.widget.SnackBar -->
<!--stuff you want inside the coordinator ... -->
</android.support.design.widget.CoordinatorLayout>
Now we are ready to do some work in the Activity to design and style after a little advanced string and color set up. Please do not be offended I am being very thorough because you seem to be very new to programming.
<string name="snackbar_text">I Am a NEW SnackBAR TEXT</string>
<string name="snackbar_action">EXIT</string>
<string name="second_text">Second Text</string>
<string name="csb_text">I am the Custom Guy</string>
<string name="csb_action">EXIT</string>
<string name="the_text">Password must have one Numeric Value\n"
"One Upper & Lower Case Letters\n"
"One Special Character $ # ! % * ? &\n"
"NO Spaces in the PASSWORD"</string>
Now for the Rainbow many ways to manage Color this is my mine.
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303f9f</color>
<color name="colorAccent">#FF4081</color>
<color name="color_Black">#000000</color>
<color name="color_White">#FFFFFF</color>
<color name="color_darkGray">#606060</color>
<color name="color_lightGray">#C0C0C0</color>
<color name="color_super_lightGray">#E0E0E0</color>
<color name="color_Red">#FF0000</color>
<color name="color_Yellow">#FFFF66</color>
<color name="color_deepBlue">#0000ff</color>
<color name="color_lightBlue">#3333FF</color>
<color name="color_Purple">#9C27B0</color>
<color name="color_Transparent">#android:color/transparent</color>
Done with house keeping in your Activity where you declare variables add this
private CoordinatorLayout myLayout;
Snackbar sb = null;
private CoordinatorLayout noActLayout;
Snackbar sbNoAct = null;
There here is the implementation of both types of Snackbars
public void makeNoAct(View view){
// this is declared on a Button android:onClick="makeNoAct"
noActLayout = (CoordinatorLayout)findViewById(R.id.coorSB);
sbNoAct = Snackbar.make(noActLayout,R.string.the_text,1);// any interger will make it happy
sbNoAct.setDuration(3000);// 3 sec // OR Snackbar.LENGTH_LONG
// matters NOT you are setting duration
View sbView = sbNoAct.getView();
sbView.setBackgroundColor(ContextCompat.getColor(this, R.color.color_Black));
TextView textViewNoAct = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
//set text color
textViewNoAct.setTextColor(ContextCompat.getColor(this,R.color.color_Yellow));
textViewNoAct.setMaxLines(10);
textViewNoAct.setTextSize(24);
//increase max lines of text in snackbar. default is 2.
sbNoAct.show();
int height = sbView.getHeight();
etNewData.setText(String.valueOf(height));
}
public void makeCOOR(View view) {
// this is declared on a Button android:onClick="makeCOOR"
// We were to Lazy to write an OnClickListener
myLayout = (CoordinatorLayout) findViewById(R.id.coorSB);
sb = Snackbar.make(myLayout, R.string.csb_text, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.csb_action, myOnClickListener)
.setActionTextColor(ContextCompat.getColor(context, R.color.color_Red));
View sbView = sb.getView();
sbView.setBackgroundColor(ContextCompat.getColor(this, R.color.color_White));
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
//set text color
textView.setTextColor(ContextCompat.getColor(this,R.color.color_deepBlue));
textView.setTextSize(30);
//increase max lines of text in snackbar. default is 2.
textView.setMaxLines(10);
// NOTE new View
TextView textAction = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_action);
//set Action text color
textAction.setTextColor(ContextCompat.getColor(this,R.color.color_Red));
textAction.setTextSize(30);
sb.show();
}
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// OR use and Intent to go somewhere have a nice trip
sb.dismiss();
System.out.println("========= I WAS DISMISSED ===============");
}
};
Enjoy the code and let us know with a comment if this solves your issue.
This is very simple to change the height or width of Snackbar .
Just we need to write 2 , 3 line of code to do this.
Check the below code snippet .
Snackbar snackbar = Snackbar.make(view, "Your message", Snackbar.LENGTH_LONG);
snackbar.setAction("Ok", new View.OnClickListener() {
#Override
public void onClick(View view) {
//your click action.
}
});
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)snackbar.getView();
layout.setMinimumHeight(50);//your custom height.
snackbar.show();
final String CR= System.getProperty("line.separator") ;
String snackMsg= "First line" + CR;
snackMsg+="Second line." +CR;
snackMsg+="... more lines." +CR;
final Snackbar snack = Snackbar.make(findViewById(android.R.id.content), snackMsg, Snackbar.LENGTH_INDEFINITE);
snack.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
// Respond to the click, such as by undoing the modification that caused
// this message to be displayed
}
});
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
// tv.setBackgroundColor(Color.RED);
tv.setLines(12);
FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
//params.height=2000;
params.bottomMargin=10;
view.setLayoutParams(params);
snack.show();
You may also need to set the size for the inner container of a snackbar in order for the text to be aligned/centered vertically. Here is a solution (Kotlin):
Snackbar.make( containerView, msg, duration ).also {
// outer container
it.view.minimumHeight = minHeightPx
// inner container
( it.view as? Snackbar.SnackbarLayout )?.getChildAt( 0 )?.let { innerView ->
innerView.minimumHeight = minHeightPx
}
}.show()
Snackbar snack = Snackbar.make(findViewById(R.id.activity_container), "Message", Snackbar.LENGTH_SHORT);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.height = 80;
tv.setTextColor(Color.WHITE);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setLayoutParams(params);
snack.show();
i have dialog and text inside eache view that i can click on .
i want all the view to be clickable insted only the text .
the code :
final Dialog dialog = new Dialog(List_Lists.this);
dialog.setContentView(R.layout.dialog_edit_tables);
dialog.setTitle("Action for " + table);
TextView delete = (TextView) dialog
.findViewById(R.id.tvDeleteTable);
TextView cancel = (TextView) dialog.findViewById(R.id.tvCancel);
OnClickListener l = new OnClickListener() {
#Override
public void onClick(View v) {
dbAdapter = new DBmethods(getApplicationContext());
switch (v.getId()) {
case R.id.tvDeleteTable:
viewListsAdapter.listsV.remove(pos);
dbAdapter.deleteTable(table);
break;
case R.id.tvCancel:
dialog.dismiss();
break;
case R.id.bTableRenameName:
if(dbAdapter.checkTableNameOK(List_Lists.this ,newName.getText().toString())){
viewListsAdapter.listsV.remove(pos);
viewListsAdapter.listsV.add(pos, newName.getText().toString().trim());
dbAdapter.renameTable(table , newName.getText().toString().trim());
renamedialog.dismiss();
};
break;
default:
break;
}
// if button is clicked, close the custom dialog
dialog.dismiss();
lv.invalidateViews();
}
};
delete.setOnClickListener(l);
cancel.setOnClickListener(l);
dialog.show();
}
});
}
as i said this code work fine if user press on text inside the view , but the empty view obviously wont respond . thanks !
if user press on red spot it activate the enter , if green than duplicate and so on...the current status is u have to press on the word , if u press on the colored spots it will do nothing
If im not wrong you need this to make layout clickable
try something like this
You can add a OnClickListener on it :
//onCreate
LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout01);
layout.setOnClickListener(yourOnClickListener);
Should be working ;)
create an id of your dialog_edit_tables
let say android:id=#+id\testing in your xml.
now write this
LinearLayout yourlayout = (LinearLayout) findViewById(R.id.testing);
yourlayout.setOnClickListener(l);
hope this will help.
You haven't shown the XML layout but setting the width of the clickable text view to fill_parent should work, also make sure your parent layout also has the width set to fill_parent.
The onClickListener is not based on the text it is based on the actual component, therefore it looks as if the layout_width attribute is set to wrap_content, so the component is only then length of the text, therefore only where the text is, is clickable. Hope this makes sense.
If I am not wrong than you are using listview or tableview to display the text.
You can do one thing. Make the textview layout_width as fill_parent That way you will able to get the touch on the place that you marked.
Hope this will help.
I have set up a working custom list view array adapter code is almost similar to the one showed here (without the cache part)
now how do I change the font of all the items to something like roboto
edit
i tried this
added private Typeface textFont; before oncreate();
TextView yourTextView = (TextView) listAdapter.getView(0, null, null);
TypefacetextFont=Typeface.createFromAsset(getApplicationContext().getAssets(),"RobotoBoldCondensed.ttf");
yourTextView.setTypeface(textFont);
Create a folder in the root of your project called assets/fonts/ then paste the TTF font file (in this case roboto.ttf).
Then use that from your adapter's getview() method like this:
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
/* create a new view of my layout and inflate it in the row */
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
/* Extract the city's object to show */
City city = getItem( position );
/* Take the TextView from layout and set the city's name */
TextView txtName = (TextView) convertView.findViewById(R.id.cityName);
txtName.setText(city.getName());
/* Take the TextView from layout and set the city's wiki link */
TextView txtWiki = (TextView) convertView.findViewById(R.id.cityLinkWiki);
txtWiki.setText(city.getUrlWiki());
Typeface face=Typeface.createFromAsset(getAssets(),"fonts/roboto.ttf");
txtName.setTypeface(face);
txtWiki.setTypeface(face);
return convertView;
}
EDIT :
Change this line,
TypefacetextFont=Typeface.createFromAsset(getApplicationContext().getAssets(),"RobotoBoldCondensed.ttf");
with,
textFont=Typeface.createFromAsset(getApplicationContext().getAssets(),"RobotoBoldCondensed.ttf");
in xml:
android:typeface
or in java:
setTypeface
Using Typeface you can change the font of your text, keep desire font ttf file in your assets folder, access and set to your desire view, just like below:
TextView txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "roboto.ttf");
txt.setTypeface(font);
For more help check Quick Tip: Customize Android Fonts
Copy your font in to your assest folder and put this code inside of your custom array adapter
TextView yourTextView = (TextView)findViewById(R.id.yourid);
Typeface textFont = Typeface.createFromAsset(context.getAssets(),"YourFont.ttf");
yourTextView.setTypeface(textFont);
It should work.
EDIT
private Typeface textFont;
Declare
#Override
public void onCreate(){
textFont = Typeface.createFromAsset(context.getAssets(),"YourFont.ttf"); }
in OnCreate() or OnStart()
and just use your custom font in your getView()
yourTextView.setTypeface(textFont);