Muaz Usmani
Muaz Usmani

Reputation: 1318

Android setting font in text view

Hi I am trying to change the font style of a TextView. I know how to change it, I have done this before I am using the following code.

public class Main_Activity extends ListActivity {
    Typeface myNewFace = Typeface.createFromAsset(getAssets(),
            "fonts/bediz__.ttf");
    private CustomListAdapter adap;

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    adap = new CustomListAdapter(this);
    setListAdapter(adap);
}
    public static class CustomListAdapter extends BaseAdapter implements
        Filterable {
           public View getView(final int position, View convertView,
            ViewGroup parent) {
        textView.setText(prayers[position]);
        holder.textLine.setTypeface(myNewFace);
           }
}

Some of the code I skipped because there is no need, by the way when I access myNewFace in getView() it ask me to make it static, when I make it static like this

static Typeface myNewFace = Typeface.createFromAsset(getAssets(),"fonts/bediz__.ttf");

It gives me the following error

Cannot make a static reference to the non-static method getAssets() from the type ContextWrapper

I dont know what to do, I have done this work several times before but now I dont know why it is not working.

Upvotes: 1

Views: 851

Answers (2)

SylvainL
SylvainL

Reputation: 3938

This is because you have declared your inner class as static; making your inner class a top-level nested class and no longer a member nested class; therefore, you cannot access any longer any non-static member of the outer class without first going through a reference to an instantiated object.

For a non-static inner class, a (hidden) reference to the outer object is always passed on when an object for an inner class is created; therefore giving access to all the members of the outer object/class. For a static inner class, this reference is not passed.

As to your sample, you could use the reference to the outer object that you are explicitly passing along when creating a new CustomListAdapter object: "adap = new CustomListAdapter(this);" but a better solution is probably to drop this static keyword from the inner class definition. You won't need to pass a reference to the outer object anymore either.

Upvotes: 1

Akram
Akram

Reputation: 7527

you have to just do this

static Typeface myNewFace = Typeface.createFromAsset(context.getAssets(),"fonts/bediz__.ttf"); 

where context should be the context of the class which is makinng call to the adapter.

Upvotes: 2

Related Questions