How do I put an external source in my app?

Asked

Viewed 5,176 times

5

I’m trying to put a custom font in my app, but I’m having too many mistakes.

I’ve tried using Pixlui, I’ve tried several different codes and always error, or the application runs, but crash (app Stopped).

This is the code I’m trying to put inside the Mainactivity.java:

TextView tx = (TextView)findViewById(R.id.textView1);
Typeface custom_font = Typeface.createFromAsset(this.getAssets(),
    "fonts/watermelon.ttf");
tx.setTypeface(custom_font);

This is the code of Mainactivity:

@SuppressWarnings("unused")
public class MainActivity extends ActionBarActivity{


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tx = (TextView)findViewById(R.id.textView1);
    Typeface custom_font = Typeface.createFromAsset(this.getAssets(),
    "fonts/watermelon.ttf");
    tx.setTypeface(custom_font);                
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();}
                }

public void opensecondactivity(View view) {
    Intent intent = new Intent(this , SecondActivity.class);
    startActivity(intent);
    overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
       } 

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent = new Intent(this , AboutActivity.class);
    startActivity(intent);
    overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
          }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
                return rootView;               
            }
     }
}

With this code Eclipse declares no error, but when it executes the Activity it error and the application is closed alone. What to do?

Just for the record, the font is in the "Assets/fonts folder"

Debug:

New_configuration [Android Application] 
    DalvikVM [localhost:8612]   
        Thread [<1> main] (Suspended (exception RuntimeException))  
            <VM does not provide monitor information>   
            ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2195    
            ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2245 
            ActivityThread.access$800(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 135    
            ActivityThread$H.handleMessage(Message) line: 1196  
            ActivityThread$H(Handler).dispatchMessage(Message) line: 102    
            Looper.loop() line: 136 
            ActivityThread.main(String[]) line: 5017    
            Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
            Method.invoke(Object, Object...) line: 515  
            ZygoteInit$MethodAndArgsCaller.run() line: 779  
            ZygoteInit.main(String[]) line: 595 
            NativeStart.main(String[]) line: not available [native method]  
        Thread [<10> Binder_2] (Running)    
        Thread [<9> Binder_1] (Running) 
        Thread [<11> Timer-0] (Running) 

Logcat:

06-14 09:58:59.484: W/ActivityThread(1243): Application com.akzonobel.malote is waiting for the debugger on port 8100...
06-14 09:58:59.494: I/System.out(1243): Sending WAIT chunk
06-14 09:58:59.584: I/dalvikvm(1243): Debugger is active
06-14 09:58:59.694: I/System.out(1243): Debugger has connected
06-14 09:58:59.744: I/System.out(1243): waiting for debugger to settle...
06-14 09:58:59.954: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.154: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.354: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.564: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.764: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.994: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:01.194: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:01.394: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:01.594: I/System.out(1243): debugger has settled (1348)
06-14 09:59:02.424: D/(1243): HostConnection::get() New Host Connection established 0xb8f54e48, tid 1243
06-14 09:59:02.514: W/EGL_emulation(1243): eglSurfaceAttrib not implemented
06-14 09:59:02.524: D/OpenGLRenderer(1243): Enabling debug mode 0
06-14 09:59:03.054: W/EGL_emulation(1243): eglSurfaceAttrib not implemented
06-14 09:59:06.384: D/AndroidRuntime(1243): Shutting down VM
06-14 09:59:06.384: W/dalvikvm(1243): threadid=1: thread exiting with uncaught exception (group=0xb1aa8ba8)
06-14 09:59:06.484: E/AndroidRuntime(1243): FATAL EXCEPTION: main
06-14 09:59:06.484: E/AndroidRuntime(1243): Process: com.akzonobel.malote, PID: 1243
06-14 09:59:06.484: E/AndroidRuntime(1243): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.akzonobel.malote/com.akzonobel.malote.MainActivity}: java.lang.RuntimeException: native typeface cannot be made
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.os.Handler.dispatchMessage(Handler.java:102)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.os.Looper.loop(Looper.java:136)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.main(ActivityThread.java:5017)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at java.lang.reflect.Method.invokeNative(Native Method)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at java.lang.reflect.Method.invoke(Method.java:515)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at dalvik.system.NativeStart.main(Native Method)
06-14 09:59:06.484: E/AndroidRuntime(1243): Caused by: java.lang.RuntimeException: native typeface cannot be made
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.graphics.Typeface.<init>(Typeface.java:175)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.graphics.Typeface.createFromAsset(Typeface.java:149)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at com.akzonobel.malote.MainActivity.onCreate(MainActivity.java:32)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.Activity.performCreate(Activity.java:5231)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-14 09:59:06.484: E/AndroidRuntime(1243):     ... 11 more
06-14 10:00:38.184: I/Process(1243): Sending signal. PID: 1243 SIG: 9

EDIT - SOLUTION: Thanks to everyone who helped me! The solution was to implement the code within the public View onCreateView. Look how it turned out:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        TextView txt = (TextView) rootView.findViewById(R.id.TextView1);
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/laouib.TTF");
        txt.setTypeface(font); 

        return rootView; 

2 answers

1


To read external fonts, I put the fonts in the root of the Asset folder and created a "Fontchanger" class that only has methods for changing fonts. All methods are static so you don’t need to instantiate the class. The only thing I pass to the method is Context. Implementation of the method within the Fontchanger class :

public static Typeface setRobotoRegular(Context context)
{
     return Typeface.createFromAsset(context.getAssets(),"roboto_regular.ttf");
}

changing the source of a textView you have in my application:

meuTextView.setTypeFace(FontChanger.setRobotoRegular(context));
  • I tested this code, but it says so: context cannot be resolved to a variable

  • Renan there I gave the example of a variable of type Context I have and has the name context. whether Voce is in a knife fragment Context context context=getActivity();

  • Finally I did it! You gave birth to me! Just implement the code inside the public View onCreateView. =D Thank you.

0

Right-click the folder "res" > New>Android Resource Diretory. Put a name of your preference in the directory and in "Resource type" select the type "font" and press ok. After that just copy your fonts into the created folder.

Note: Before copying the fonts, rename and remove all the special characters and strokes, because Android Studio does not accept files with names like this.

Example: DS-DIGITAL.TFF >>>>>> dsdigital.tff!

Source: https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xmlinserir a descrição da imagem aqui

Browser other questions tagged

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