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);
}
}
2
Answers
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
Rewrite your
MainActivity
as