How to dynamically set the text size in multiple textviews forming the rows of a list view?

I’ve been looking at this for a few days now, but to no avail (yet!)

As the question says – I’m trying to dynamically alter the size of the text displayed in a listview. My xml is set up to describe each row in the listview as having an image view (icon) and a textview (label).

I want to adjust the size of the text within all the ‘label’ textviews in the list view in one go, in two situations: 1) in response to a button click in the current activity 2) in response to a value read from shared preferences

I believe I can make use of the setTextAppearance method. This is my code – it runs without errors, but then it also does not have the desired effect!

I would be very grateful for any thoughts you have on this. Best wishes Steven

import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class IndexCustomAdapter extends ArrayAdapter<String>
{
LayoutInflater inflater;
String[] indexContents;
String[] scores;

private SharedPreferences spSettings;

public IndexCustomAdapter(Context context, int indexRowId, String[] objs) 
{
    super(context, indexRowId, objs);
    inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    indexContents = objs;
    spSettings = getContext().getSharedPreferences("settings", 0);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null)
    {
        convertView = inflater.inflate(R.layout.indexrow, parent, false);
    }

    TextView label = (TextView) convertView.findViewById(R.id.label);
    ImageView icon = (ImageView) convertView.findViewById(R.id.icon);

    // Select the correct text size
    int fontSize = spSettings.getInt("fontSize", 16);
    switch (fontSize)
    {
        case 24:
            label.setTextAppearance(getContext(), android.R.attr.textAppearanceLarge);
            break;
        case 20:
            label.setTextAppearance(getContext(), android.R.attr.textAppearanceMedium);
        case 16:
            label.setTextAppearance(getContext(), android.R.attr.textAppearanceSmall);
    }       

    label.setText(indexContents[position]);
    }
}

Answer

In your button’s onClickListener save the new font size to your shared preferences, then use the notifyDataSetChanged method. I’m thinking something like this.

button.SetOnclickListener(new OnclickListener(){
    public void onClick(View v){
        //Update shared preferences with desired
        //font size here

        //Instance of your IndexCustomAdapter that you attatched to your listview
        indexCustomAdapter.notifyDataSetChanged();

    }
})

Leave a Reply

Your email address will not be published. Required fields are marked *