How to change attributes of all project Textviews at runtime?

Asked

Viewed 169 times

1

I am implementing a visual settings section of a project and one of the settings should allow the user to change the fontFamily of all texts, there is also the option to leave all texts uppercase or lowercase. I know it’s possible to capitalize a textView using textAllCaps, but I haven’t found anything about fontFamily, nor about applying these settings to the entire project. Is there any way to solve this problem? Grateful from now on.

The project still has nothing ready regarding the change of all textViews, because I do not know how to do this. But I’ll leave the Activity code settings.

Configuration XML Activity:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/btn_back"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_marginTop="8dp"
            android:background="@drawable/purple_right_rounded_backgroud"
            android:onClick="backToMainScreen"
            android:padding="4dp"
            app:layout_constraintBottom_toTopOf="@+id/guideline8"
            app:layout_constraintStart_toStartOf="@+id/guideline18"
            app:srcCompat="@android:drawable/ic_menu_revert" />

        <TextView
            android:id="@+id/textView19"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginRight="70dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="CONFIGURAÇÕES"
            android:textAllCaps="true"
            android:textSize="24sp"
            android:textStyle="bold"
            app:fontFamily="casual" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/yellow_mustard"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView30"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/background_maincolor_dark"
            android:gravity="center"
            android:text="Tipo de letra"
            android:textAllCaps="true"
            android:textColor="@android:color/white"
            android:textSize="20dp"
            android:textStyle="bold"
            app:fontFamily="casual" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="4dp">

            <RadioGroup
                android:id="@+id/rgLetterType"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:background="@drawable/white_rounded_backgroud">

                <RadioButton
                    android:id="@+id/rb_casual"
                    android:layout_width="110dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="CASUAL" />

                <RadioButton
                    android:id="@+id/rb_cursiva"
                    android:layout_width="110dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="CURSIVA" />

                <RadioButton
                    android:id="@+id/rb_bastao"
                    android:layout_width="110dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="BASTÃO" />

                <RadioButton
                    android:id="@+id/rb_imprensa"
                    android:layout_width="110dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="IMPRENSA" />

            </RadioGroup>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/textView32"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Visualização:"
                    android:textAllCaps="true"
                    android:textSize="14sp" />

                <TextView
                    android:id="@+id/textView31"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="4dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    app:fontFamily="casual" />

            </LinearLayout>

        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/yellow_mustard"
        android:orientation="vertical">

        <TextView
            android:id="@+id/otherConfigs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/background_maincolor_dark"
            android:gravity="center"
            android:text="Outros ajustes"
            android:textAllCaps="true"
            android:textColor="@android:color/white"
            android:textSize="20dp"
            android:textStyle="bold"
            app:fontFamily="casual" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="4dp">

            <TextView
                android:id="@+id/textView21"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="As letras devem ser:"
                android:textAllCaps="true"
                android:textSize="18sp" />

            <RadioGroup
                android:id="@+id/rgLetterCase"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:background="@drawable/white_rounded_backgroud"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/rb_uppercase"
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="MAIÚSCULA" />

                <RadioButton
                    android:id="@+id/rb_lowercase"
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="MINÚSCULA" />

            </RadioGroup>

        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Controller of Activity settings:

package com.example.anaplb.appalpha.activities;

import android.support.v7.app.Appcompatactivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Radiobutton; import android.widget.Radiogroup;

import com.example.anaplb.appalpha. R; import com.example.anaplb.appalpha.config.Appconfig;

public class Configactivity extends Appcompatactivity { private Appconfig Configurator; private Radiogroup rgLetterType; private Radiobutton rbCasual; Private Radiobutton rbCursiva; private Radiobutton rbBastao; Private radiobutton rbImprensa;

private RadioGroup rgLetterCase;
private RadioButton rbUpper;
private RadioButton rbLower;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_config);

    this.rgLetterType = findViewById(R.id.rgLetterType);
    this.rgLetterCase = findViewById(R.id.rgLetterCase);
    this.rbCasual = findViewById(R.id.rb_casual);
    this.rbCursiva = findViewById(R.id.rb_cursiva);
    this.rbBastao = findViewById(R.id.rb_bastao);
    this.rbImprensa = findViewById(R.id.rb_imprensa);
    this.rbUpper = findViewById(R.id.rb_uppercase);
    this.rbLower = findViewById(R.id.rb_lowercase);

    this.configurator = AppConfig.getInstance(getApplicationContext());


}

@Override
protected void onResume() {
    super.onResume();
    loadConfigsInView();
}

public void backToMainScreen(View view){
    finish();
}

@Override
protected void onPause() {
    super.onPause();
    pushChanges();
    this.configurator.saveAllChange(getApplicationContext());
}

private void pushChanges(){
    String rgSelectedLetterType =((RadioButton)findViewById(this.rgLetterType.getCheckedRadioButtonId())).getText().toString();
    String rgSelectedLetterCase =((RadioButton)findViewById(this.rgLetterCase.getCheckedRadioButtonId())).getText().toString();
    this.configurator.setCurrentLetterType(rgSelectedLetterType);
    this.configurator.setCurrentLetterCase(rgSelectedLetterCase);
}

private void loadConfigsInView(){
    Log.i("Json-Config","Entrou em LoadConfigs");
    Log.i("Json-Config","CurrentLetterType: " + this.configurator.getCurrentLetterType());
    Log.i("Json-Config","CurrentLetterCase: " + this.configurator.getCurrentLetterCase());
    switch(this.configurator.getCurrentLetterType()){
        case(AppConfig.CASUAL):
            rgLetterType.check(rbCasual.getId());
            Log.i("Json-Config","CASUAL");
        break;

        case(AppConfig.CURSIVA):
            rgLetterType.check(rbCursiva.getId());

            Log.i("Json-Config","CURSIVA");
        break;

        case(AppConfig.BASTAO):
            rgLetterType.check(rbBastao.getId());

            Log.i("Json-Config","BASTAO");
        break;

        case(AppConfig.IMPRENSA):
            rgLetterType.check(rbImprensa.getId());

            Log.i("Json-Config","IMPRENSA");
        break;

    }

    switch(this.configurator.getCurrentLetterCase()){
        case(AppConfig.UPPER):
            rgLetterCase.check(rbUpper.getId());
            Log.i("Json-Config","UPPER");
        break;

        case(AppConfig.LOWER):
            rgLetterCase.check(rbLower.getId());
            Log.i("Json-Config","LOWER");
        break;

    }
}

}

  • Have you tried youTextView.setTypeface(Typeface.create("sans-Serif-light", Typeface.NORMAL)); ? An alternative to changing all fonts of the project’s textview, is to create a subclass that extends from Textview, use a sharedpreference to retrieve the configuration the user placed, and then return it in their custom textview. Add your code, which I try to help better.

  • Thanks for the tips buddy, I’ll try to implement them. About persistence of user settings, I’m using JSON to save/recover, what do you think?

  • I created an Alphatextview class that extends from Textview, but I don’t know how I can make all the Alphatextview I use change by changing some of the settings I implemented on the settings screen. I would have to somehow have a list of all the Alphatextviews used?

  • I will make one here, using sharedpreference ai you modify to use with the Json you receive. I will soon command.

  • Okay, I went up the example on github if you want to take a look. Anything just ask

2 answers

1

It has 2 ways to change the fontFamily:

  • Using the method setTypeface():

    • textView.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
    • TextView.setTypeface(ResourcesCompat.getFont(context, R.font.YOUR_FONT));
    • TextView.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/mycustomfont.ttf"));
  • Using the method setTextAppearance():

    Create a style for each configuration and apply it to Textview using the method setTextAppearance().

    Styles.xml

    <style name="styleCausal">
        <item name="android:fontFamily">causal</item>
    </style>
    <style name="styleSans-serif">
        <item name="android:fontFamily">sans-serif</item>
    </style>
    

    Java

    if(isCausal){
        textView.setTextAppearance(R.style.styleCausal);
    }else{
        textView.setTextAppearance(R.style.styleSans-serif);
    }
    

The setTextAppearance() has the advantage that more than one characteristic can be declared at the same time, using <item name=""></item>.

Other how to amend/define the appearance of text throughout the application is using themes.
A certain theme can be "set" through setTheme(). However it will have to be done in the onCreate() and before setContentView().

0


Creates this class that will extend from Textview:

public class NewTextView extends AppCompatTextView {
    private Context context;
    private String fontFamily;


    public NewTextView(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public NewTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public NewTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init();
    }



    private void init() {
        //Eu criei sharedpreferences apenas para meu teste
        //No seu caso recupere os valores pelo seu próprio Json
        SharedPreferences preferences;
        preferences = context.getSharedPreferences(USER_FONTFAMILY, Context.MODE_PRIVATE);
        if (preferences != null) {
            fontFamily = preferences.getString(FONTFAMILY, null);

            if (fontFamily != null) {
                switch (fontFamily) {
                    case CASUAL: {
                        Typeface tf = Typeface.create("sans-serif", Typeface.NORMAL);
                        setTypeface(tf);
                        break;
                    }
                    case CURSIVA: {
                        Typeface tf = Typeface.create("serif-monospace", Typeface.NORMAL);
                        setTypeface(tf);
                        break;
                    }
                    case BASTAO: {
                        Typeface tf = Typeface.create("sans-serif-smallcaps", Typeface.NORMAL);
                        setTypeface(tf);
                        break;
                    }

                }
            }
        } else {
            //default
            Typeface tf = Typeface.create("sans-serif", Typeface.BOLD_ITALIC);
            setTypeface(tf);
        }

    }
}

Instead of Sharedpreference, you recover the user’s configuration by Json, in this example I used sharedpreference only to test even.

In the xmls files that contain the textviews, it changes ALL of them to:

        <seupacotecompleto.NewTextView
        android:layout_width="wrap_content"
        android:id="@+id/seuID"
        android:layout_height="wrap_content"
        android:text="Seu texto"/>

If you want to see the full example I did to test, I put it on my github:

https://github.com/MurilloComino/ConfigTextviewFontFamily

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.