How to let the user decide a font for a button? - java

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

Related

How make several font style selection (Typeface & SharedPreferences)

I don't know how to store font style using sharedpreferences or if there is any other method please support me.
// Load Text Font start
SharedPreferences myTextFont = this.getSharedPreferences("MyTextFont", MODE_PRIVATE);
textFont = myTextFont.getInt("font", textExample.getTypeface().getStyle());
textView3.setTypeface(null,textFont);
// Load Text Font end
//textExample.setTypeface(textFont);
//Font Buttons start
final Typeface typeface1 = ResourcesCompat.getFont(this,R.font.teqnikuri);
type_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textExample.setTypeface(typeface1);
SharedPreferences myTextFont = getSharedPreferences("MyTextFont", MODE_PRIVATE);
SharedPreferences.Editor editor = myTextFont.edit();
editor.putInt("font", textExample.getTypeface().getStyle());
editor.commit();
}
});

Save LinearLayout with multiple TextView. Android

I have method. They add a new number (with different colors and gravity), each time you press the button. After some clicks i have LinearLayout with multiple TextView. And i dont understand, how to save it. After closing the application, it opens with a blank layout. But i need to save previous TextView's.
public void someText(String message) {
TextView message = new TextView(MainActivity.this);
message.setText(message);
message.setBackgroundResource(R.drawable.textsmallest);
message.setTextColor(getResources().getColor(R.color.black));
message.setGravity(Gravity.START);
messageLayout.addView(message);
(I am really sorry, english is not my native language.)
You can use SharedPreferences save message or other value to xml.
Link this:
Context ctx = MainActivity.this;
SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("STRING_KEY", "string");
editor.putInt("INT_KEY", 0);
editor.putBoolean("BOOLEAN_KEY", true);
editor.commit();

Changing typeface of Snackbar

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

Change font of all list items in a list view

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

How do I tell if a TextView created in my SQLite database was clicked?

I have a database with team names and team numbers(both stored as strings - the numbers sometimes have letters in them)
I want it so when you click the "Open" button, it'll bring up a popup that will have all of the teams' names and numbers, and if you click one, it will close the popup and set both editText's to the name & number.
Dialog d = new Dialog(this);
ScoutingFormData info = new ScoutingFormData(this);
info.open();
ScrollView scr = info.getData();
info.close();
d.addContentView(scr, null);
d.show();
That's from the main program, when you click "Open", this happens. ScoutingFormData is my SQLite database, and here's getData:
public ScrollView getData() {
String[] columns=new String[]{KEY_ROWID,KEY_NAME,KEY_NUM};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
ScrollView result=new ScrollView(null);
int iID = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iNum = c.getColumnIndex(KEY_NUM);
LinearLayout vertlay = new LinearLayout(null);
vertlay.setOrientation(LinearLayout.VERTICAL);
for (c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
TextView tv=new TextView(null);
tv.setText(c.getString(iNum)+" "+c.getString(iName));
vertlay.addView(tv);
}
result.addView(vertlay);
return result;
}
So this builds the dialog, but how do I make it so the main program(the top code) will know when one of these TextViews have been clicked?
Side question: when making a View(like LinearLayout vertlay = new LinearLayout(null);), what context am I supposed to be using? I don't fully understand what a 'context' is, so I'm really at a loss of what to replace "null" with.
How do I make it so the main program(the top code) will know when one of these TextViews have been clicked?
Simply make tv clickable and add an OnClickListener.
Side question: what context am I supposed to be using?
You hinted that getData() is in your database adapter class ScoutingFormData, save a reference to the Context passed to the Constructor and reuse it later:
private Context mContext;
public ScoutingFormData(Context context) {
mContext = context;
}
All together:
TextView tv=new TextView(mContext);
tv.setClickable(true);
tv.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Do something
}
});

Categories

Resources