skip to Main Content

I’m a beginner.
I’m trying to make Locale project with Android Studio.
So I made a class regard with Context.
In MainActivity required a constructor.
But, I’m heard that MainActivity do not need constructor but onCreate.

Here is my code.

BaseContextWrapper

    public class BaseContextWrapper extends AppCompatActivity {
    //AppCompatActivity-FragmentActivity-ComponentActivity-Activity-ContextThemeWrapper-ContextWrapper-Context
    public BaseContextWrapper(Context base) {
        super.attachBaseContext(base);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @NonNull
    public static ContextWrapper wrap(Context context) {
        Resources resources = context.getResources();
        Configuration newConfig = new Configuration();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        newConfig.setToDefaults();

        newConfig.densityDpi = metrics.densityDpi;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            context = context.createConfigurationContext(newConfig);
        } else {
            resources.updateConfiguration(newConfig, resources.getDisplayMetrics());
        }
        return new BaseContextWrapper(context);
    }
}

MainActivity

    public class MainActivity extends BaseContextWrapper {
    public MainActivity(Context base) {
        super(base);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

warning image

2

Answers


  1. It all depends on what you inherit from. If from "extends Base ContextWrapper", then the constructor is required, it is included in the class. But if from "extends AppCompatActivity" then nothing but the onCreate() method is needed

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    Login or Signup to reply.
  2. Rewrite your MainActivity as

    public class MainActivity extends AppCompatActivity {
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search