Use of external class with error (non-static method)

0

I created an external Class tag to leave some methods that I always use, but it is giving error when using them, / em>:

package com.hs.gui.testelayout.util;

import android.support.v7.app.AppCompatActivity;
/**
 * Created by Gui_j on 25/04/2016.
 */
public class Util extends AppCompatActivity {

    public void backAppBar(String telaTitulo){
     //getSupportActionBar() são métodos nativos do _Android_ que chamam um botão na tela
     getSupportActionBar().setDisplayHomeAsUpEnabled(true);
     getSupportActionBar().setHomeButtonEnabled(true);
     getSupportActionBar().setTitle(telaTitulo);
    }
}

If I keep the way it is there, I have a return error:

TogettheerrorIshouldmake

publicvoidbackAppBar(StringtelaTitulo){...}

in

publicstaticvoidbackAppBar(StringtelaTitulo){...}

ButdoingthisIgainanothererror:

ThattocorrectImustremovethestaticadded,butwiththatwereturntotheinitialproblem.About getSupportActionBar()

    
asked by anonymous 25.04.2016 / 21:27

1 answer

3

This occurs because the getSupportActionBar method is not static, so it will not have access in a static method.

There are two ways to resolve this:

Abstract Class

This class will have all methods common to the other Screens.

Example:

public abstract class ActivityModel extends AppCompatActivity{
    public void backAppBar(String telaTitulo){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setTitle(telaTitulo);
    }

}

On your screens, instead of extending from AppCompatActivity , you should extend from ActivityModel :

public class MainActivity extends ActivityModel {
…
}

Utility Class

Another way would be to create a utility class with common methods. The difference is that instead of inheriting, you should pass the information from Activity (as seen in the comments above to DiegoF ):

public class Utils  {
    public static  void backAppBar(String telaTitulo, AppCompatActivity activity){
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        activity.getSupportActionBar().setHomeButtonEnabled(true);
        activity.getSupportActionBar().setTitle(telaTitulo);
    }

}

    
25.04.2016 / 22:15