0

2 つの Java クラスがあり、そのうちの 1 つはそのアクティビティ クラスから、アクティビティ クラスではない 2 番目のクラスの関数を呼び出したいのですが、Font クラス内で関数 GetRobotoRegularFont を呼び出すと、「Caused by」というエラーが表示されます。 :

java.lang.NullPointerException
at com.ojaswi.font.Font.GetRobotoRegularFont(Font.java:16)
at com.ojaswi.bookingscapemob.LoginActivity.onCreate(LoginActivity.java:29)

「..2 つの Java ファイルのコードは..誰か助けてください..

最初の Java ファイルのコード

public class LoginActivity extends Activity {

EditText email;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    email = (EditText)findViewById(R.id.edtTextUname);
    email.setTypeface(new Font().GetRobotoRegularFont());


}

}

2 番目の Java ファイルのコード

public class Font {

Typeface tf;
Context myContext;
public final Typeface GetRobotoRegularFont() {
    String fontPath = "fonts/Roboto-Regular.ttf";
    tf = Typeface.createFromAsset(myContext.getAssets(), fontPath);
    return tf;
}

}

4

3 に答える 3

3

You never do set Context in the Font class.

Options:

  • Add context to the constructor
  • Add a setter method for the context field
  • If you don't use the Font class in other places you can inline the code like Raghunandan did propose
于 2013-03-12T09:36:30.857 に答える
1

LoginActivity では、このように記述します

email.setTypeface(new Font().GetRobotoRegularFont(this));

そして Font クラスで

public class Font {

Typeface tf;
Context myContext;
public final Typeface GetRobotoRegularFont(Context context) {
    myContext = context;
    String fontPath = "fonts/Roboto-Regular.ttf";
    tf = Typeface.createFromAsset(myContext.getAssets(), fontPath);
    return tf;
}
于 2013-03-12T10:27:06.653 に答える
0

Assuming that the file is in assets folder you can do the following.

 Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/verdana.ttf");
 email = (EditText)findViewById(R.id.edtTextUname);
 email.setTypeface(tf,Typeface.BOLD);
于 2013-03-12T09:36:34.023 に答える