how to programatically theme an activity to be like a dialog? - java

Question
How does one programatically (without touching the AndroidManifext.xml) set the theme of an Activity so that it looks like a dialog?
Note: I am ok with modifying the AndroidManifext.xml as long as it does not need to be modified in order to switch between making it look like a normal activity or a dialog.
What I've tried so far
I tried the following as per this stackoverflow answer:
public class DialogActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(android.R.style.Theme_DeviceDefault_Dialog);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
Log.d(TAG,"Build.VERSION.SDK_INT: "+Build.VERSION.SDK_INT); // 23
}
}
But it ends up blacking out everything in the background.
I also saw this stackoverflow answer, and tried:
public class DialogActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(android.R.style.Theme_DeviceDefault_Dialog);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
}
but it ends up making everything black.
What do? Thank you.

Background
The Activity behind an Acivity is drawn if the foreground activity's theme according to its AndroidManifest.xml is a dialog; otherwise the android os will not draw the Activity behind it (probably to save memory since it usually won't be seen anyway).
To exploit this, we set the theme of our Acitvity to a dialog in the manifest, making the android os draw the Activity behind it, but later, programatically set our Activity's theme to whatever we like at runtime.
Example on github
I made an example and put it on github.
Tutorial
Step 1: create two custom themes for your application in styles.xml. One for normal activities, and another for dialog activities. It is important for the custom dialog theme to inherit from a base theme that is also a dialog. In my case, the parent theme is Base.Theme.AppCompat.Light.Dialog.FixedSize). Here is my styles.xml:
<resources>
<!-- custom normal activity theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
<!-- custom dialog activity theme -->
<style name="AppTheme.Dialog" parent="Base.Theme.AppCompat.Light.Dialog.FixedSize">
<!-- removing the dialog's action bar -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
</resources>
Step 2: in the AndroidManifest.xml, set the theme of the Activity in question to any dialog theme. This makes the android os think that the Activity is a dialog, so it will draw the Activity behind it, and not black it out. In my case, I used Theme.AppCompat.Dialog. Below is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.eric.questiondialog_artifact">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name">
<activity
android:name=".DialogActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Dialog"> <-- IMPORTANT!!! -->
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Step 3: in the actual activity, set the theme programatically to either the theme for normal activities, or the theme for dialogs. My DialogActivity.java is below:
package com.example.eric.questiondialog_artifact;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class DialogActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(R.style.AppTheme_Dialog); // can either use R.style.AppTheme_Dialog or R.style.AppTheme as deined in styles.xml
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
}
}

if what you're looking for is just a theme with transparent background for you activity, just use this:
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
apply this style to your activity in your AndroidManifest file and this is it

I am late but still for future users
you need to call the below code after setTheme() Calling this allows the Activity behind this one to be seen again. Once all such Activities have been redrawn
// setTheme()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Method getActivityOptions = Activity.class.getDeclaredMethod("getActivityOptions");
getActivityOptions.setAccessible(true);
Object options = getActivityOptions.invoke(activity);
Class<?>[] classes = Activity.class.getDeclaredClasses();
Class<?> translucentConversionListenerClazz = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz;
}
}
Method convertToTranslucent = Activity.class.getDeclaredMethod("convertToTranslucent",
translucentConversionListenerClazz, ActivityOptions.class);
convertToTranslucent.setAccessible(true);
convertToTranslucent.invoke(activity, null, options);
} catch (Throwable t) {
}
} else {
try {
Class<?>[] classes = Activity.class.getDeclaredClasses();
Class<?> translucentConversionListenerClazz = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz;
}
}
Method method = Activity.class.getDeclaredMethod("convertToTranslucent",
translucentConversionListenerClazz);
method.setAccessible(true);
method.invoke(activity, new Object[] {
null
});
} catch (Throwable t) {
}
}

Try these code before dailog.setMessage(...);
Dialog id = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
//Default theme
Try this for Old theme
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_TRADITIONAL);
Try these for KITKAT theme
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK); //Dark
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_HOLO_LIGHT);
Try these codes for Pragmatically
Exmaple
dialog = new AlertDialog.Builder(this);
dialog = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);
dialog.setTitle("HAI");
dialog.setMessage("look");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
Toast toast= Toast.makeText(getApplicationContext(), "This is exmaple theme", Toast.LENGTH_LONG);

Related

How to remove the green bar on a android app in android studio

Like the title, I am wondering how to get rid of the green bar at the top so that it matches the background of the activity. I have no idea where to look I've had a look in the manifest and haven't found anything.
What do I do so that it matches the background of the activity?
Note. Different activities have different backgrounds, so is there a way that I just match the activity it is on?
The green bar is called Status bar, and to hide it in activity call below method in onCreate()
void hideStatusBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(uiOptions);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
And to hide it in a fragment, call it in onCreateView()
void hideStatusBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
requireActivity().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
} else {
requireActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
You can change status bar color using this extension function, call this function from Activity just passing the color
fun AppCompatActivity.changeStatusBarColor(#ColorRes color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.statusBarColor = ContextCompat.getColor(this, color)
}
}
go to following path:
app->res->values->styles
and here in style tag three item tags are available, in that colour of first and last item keep same.
then app status bar and action bar colour display same.
Example:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here.
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
-->
<item name="colorPrimary">#FFA500</item>
<item name="colorPrimaryDark">#FFA500</item>
</style>

Alert Dialog in RecyclerView Adapter

I've implemented a long click listener to delete an entry from my recyclerview and I'd like to give the user one last chance to change their mind. I've done something similar in a 'standard' view using an Alert Dialog and i've made a few drawables for the buttons in the alert view that I would like to use again (to keep a constant interface among all my views)
The drawable I'm using is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/minus_button"
android:state_pressed="false"
android:state_selected="false"/>
<item android:drawable="#drawable/add_button"
android:state_pressed="true"/>
</selector>
The alert I'm trying to use is :
public void deleteRequestCheck(final int tempIDval){
AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
builder.setMessage("Are you sure you want to reset all your climbs back to zero?");
builder.setCancelable(false);
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteEntry(tempIDval);
}
});
AlertDialog alert = builder.create();
alert.show();
Button nbutton = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setBackgroundColor(getDrawable(R.drawable.button_tap));
nbutton.setTextColor(Color.WHITE);
Button pbutton = alert.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(getDrawable(R.drawable.button_tap));
pbutton.setTextColor(Color.WHITE);
}
and I'm calling this from inside my Adapter class (where the longclick action is handled).
The issue I'm having is that
nbutton.setBackgroundColor(getDrawable(R.drawable.button_tap));
pbutton.setBackgroundColor(getDrawable(R.drawable.button_tap));
are giving me an error that it Cannot resolve method 'getDrawable(int)'. This has me stumped as this is identical to how I've created and called this alert dialog in my previous activities.
There are actually 2 ways you can do this:
1) Programmatically like:
nbutton.setBackground(ContextCompat.getDrawable(this.context‌​, R.drawable.mypositiveButtonDrawable));
But what if you want same button color for other dialogs? Why to duplicate the effort?
2) through styles.xml
Create a theme in your styles.xml like:
<style name="DiscardChangesDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="buttonBarNegativeButtonStyle">#style/DialogButtonNegative</item>
<item name="buttonBarPositiveButtonStyle">#style/DialogButtonPositive</item>
</style>
<style name="DialogButtonNegative" parent="Widget.AppCompat.Button.Borderless">
<item name="android:textColor">#color/dialog_button_negative</item>
</style>
<style name="DialogButtonPositive" parent="Widget.AppCompat.Button.Borderless">
<item name="android:textColor">#color/dialog_button_positive</item>
</style>
and then use it like:
AlertDialog.Builder(this, R.style.DiscardChangesDialog)
and then you do not need to worry about adapter or anything.
Hope it helps!!!

Setting header colour in the new Material DatePicker

So am trying to change the colour of the header of my DatePicker. It doesn't appear to as easy as first though. You can do it in the XML like so:
android:headerBackground="#color/myColor" />
However there doesn't seem to be a way to be able to do this in code. The usual setters don't seem to be apparent (i.e datePicker.setHeaderBackground).
Any ideas?
Create custom datepicker dialog. See this link once.
You can use setAccentColor() for change color of header in this sample. use it like dpd.setAccentColor(Color.BLUE);.
If you don't want this color to buttons, just remove below lines from 'DatePickerDialog' class.
okButton.setTextColor(mAccentColor);
cancelButton.setTextColor(mAccentColor);
Here is the method to change header background of DatePickerDialog:
private void setDatePickerHeaderBackgroundColor(DatePickerDialog dpd, int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Field mDatePickerField;
mDatePickerField = DatePickerDialog.class.getDeclaredField("mDatePicker");
mDatePickerField.setAccessible(true);
final DatePicker mDatePicker = (DatePicker) mDatePickerField.get(dpd);
int headerId = Resources.getSystem().getIdentifier("day_picker_selector_layout", "id", "android");
final View header = mDatePicker.findViewById(headerId);
header.setBackgroundColor(color);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
As you can see I'm using java reflection for Lollipop and above to get header view.
Usage:
DatePickerDialog dpd = new DatePickerDialog(this, this, 2016, 0, 11);
setDatePickerHeaderBackgroundColor(dpd, getResources().getColor(android.R.color.black));
dpd.show();
As a result we have:
EDIT:
In case you just want to set header background of DatePicker, that you've created in xml, forgot about java reflection, just use these lines to get it working:
DatePicker mDatePicker = (DatePicker) findViewById(R.id.date_picker);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int headerId = Resources.getSystem().getIdentifier("day_picker_selector_layout", "id", "android");
final View header = mDatePicker.findViewById(headerId);
header.setBackgroundColor(getResources().getColor(android.R.color.black));
}
create this style :
<style name="MyDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/chosen_header_bg_color</item>
</style
and add this style to your dialog theme :
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">#style/MyDatePickerStyle</item>
</style>
and add this dialog to your app theme :
<style name="MyDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/chosen_header_bg_color</item>
</style>
it is very wll explained here : Change Datepicker dialog color for Android 5.0
and this did work for me.
You need to override your DatePickerStyle, follow the steps,
1) Override DatePickerDialogTheme inside your app's base theme:
<style name="AppBaseTheme" parent="android:Theme.Material.Light">
....
<item name="android:datePickerDialogTheme">#style/CustomDatePickerDialogTheme</item>
</style>
2) Define CustomDatePickerDialogTheme
<style name="CustomDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">#style/CustomDatePickerStyle</item>
</style>
3) Overridden DatePickerStyle with the style CustomDatePickerStyle
<style name="CustomDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/header_bg_color</item>
</style>
Hope it helps.
Edit: Sorry for missing out the code part,
Use this style to create DatePickerDialog like this:
new DatePickerDialog(getActivity(),R.style.CustomDatePickerStyle, this, year, month, day);

getActionBar() returns NULL in actionBar

I am currently creating the actionBar in android studio and I have created action buttons and my aim is to have a dropdown menu everytime I click a button.
In my menu_main.xml, I added the items search and help:
<item
android:id="#+id/menu_search"
android:icon="#drawable/ic_action_search"
android:title="#string/menu_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="collapseActionView|ifRoom"/>
<item android:id="#+id/action_help"
android:icon="#drawable/ic_action_help"
android:title="#string/action_help"
app:showAsAction="ifRoom"/>
In my MainActivity.java, I have added the Strings for my dropdown:
String[] actions = new String[] {
"Bookmark", "Subscribe", "Share", "Like"
};
In my onOptionsItemSelected() method, i have added the case where everytime you click on this button, it will call a function. Here is my code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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.
switch (item.getItemId()) {
case R.id.action_help:
helpMessage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void helpMessage() {
//Toast.makeText(this, "Location button pressed", Toast.LENGTH_SHORT).show();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, actions);
System.out.println("HERE: " + getActionBar());
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
Toast.makeText(getBaseContext(), "You selected : " + actions[itemPosition], Toast.LENGTH_SHORT).show();
return false;
}
};
getActionBar().setListNavigationCallbacks(adapter, navigationListener);
}
When I run the program, my app will crash and I get
NullPointerException: Attempt to invoke virtual method 'void
android.app.ActionBar.setNavigationMode(int)' on a null object
reference
It points to getActionBar() which is NULL.
Any thoughts?
I always have this error....
I found a solution which I put this to my Style it will be work and getActionBar() won't be null anymore...
<item name="android:windowNoTitle">false</item>
<item name="android:windowActionBar">true</item>
Hope this help you
Use getSupportActionBar() instead of getActionBar(). Also theme of your activity should be extended of Theme.AppCompat.
I think you should
1.Check themes
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
2.Check your Activity class , it's extend AppcombatActivity or ActionBarActivity
So, I hope it useful for you

Android display Splash-Screen while loading

I have an Android App, which shows a "Splash Screen" for 3 seconds. After that, the MainActivity gets loaded.
Unfortunately the MainActivity takes additional ~4 seconds to load. On first startup even longer. However when the App is loaded, everything runs smooth.
Now how can I achieve it, that the MainActivity gets loaded, during the display of the Splash Screen? It just should display an image until the whole thing loaded completely.
I have read about Async-Task, but I'm not sure where to put it and how to use it properly. Can someone help me please?
SplashScreen.java
public class SplashScreen extends Activity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
MainActivity.java
public class MainActivity extends Activity implements OnClickListener, MediaController.MediaPlayerControl {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Some heavy processing
//starting services
//starting Google Text to Speech
//and so on...
}
}
You should not be creating a new thread on startup, instead you should create a view that does not have to wait for your resources to load, as detailed in this article: Splash Screens the Right Way.
As stated in the article, you should create a layer-list drawable instead of a layout XML file:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Fill the background with a solid color -->
<item android:drawable="#color/gray"/>
<!-- Place your bitmap in the center -->
<item>
<bitmap
android:gravity="center"
android:src="#mipmap/ic_launcher"/>
</item>
</layer-list>
Then create a theme using the drawable file as a background. I use the background attribute instead of the windowBackground attribute as suggested in the article, because background takes the status and navigation bars into account, centering the drawable better. I also set windowAnimationStyle to null so that the splash screen does not animate the transition to the MainActivity:
<resources>
<!-- Base application theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<!-- Splash Screen theme -->
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:background">#drawable/background_splash</item>
<item name="android:windowAnimationStyle">#null</item>
</style>
</resources>
Then declare your theme in the manifest for your SplashActivity:
<activity android:name=".SplashActivity"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And finally all you have to do in your SplashActivity is start your MainActivity, and the splash screen will only show for as long as it takes for your app to configure:
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
If there are no specific constraints about the time the splash screen should be shown, you could use the AsyncTask in the following way:
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup);
startHeavyProcessing();
}
private void startHeavyProcessing(){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//some heavy processing resulting in a Data String
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "whatever result you have";
}
#Override
protected void onPostExecute(String result) {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra("data", result);
startActivity(i);
finish();
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
If the resulting data if of another nature than a String you could put a Parcelable Object as an extra to your activity. In onCreate you can retrieve the data with:
getIntent().getExtras.getString('data');
How about, in the interest of simplicity, you combine your splash activity with your main activity? That way you get the best of both worlds, namely a splash screen while your data is preparing the first time, and a quick startup when it's been prepared previously. Making the user wait for nothing is not really good form...
Something like:
public class MainActivity extends Activity implements OnClickListener, MediaController.MediaPlayerControl {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initially shows splash screen, the main UI is not visible
setContentView(R.layout.activity_main);
// Start an async task to prepare the data. When it finishes, in
// onPostExecute() get it to call back dataReady()
new PrepareDataAsyncTask(this).execute();
}
public void dataReady() {
// Hide splash screen
// Show real UI
}
}
your splash screen code works fine but when you call next activity then in onCreate() use Asynctask for your heavy tasks...
I have had similar problem. There was a blank loading screen (not even toolbar). Mu culprit was in the manifest in the MainActivity:
android:launchMode="singleInstance"
Just do like in this article:
1 - create a XML layout like this for the splash screen. I called it "background_splash.xml"
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="#color/cardview_light_background"/>
<item>
<bitmap
android:gravity="center"
android:src="#drawable/kiss_com_sub_logo"/>
</item>
</layer-list>
2 - Then, go to the styles.xml and write a style like this:
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">#drawable/background_splash</item>
</style>
3 - Write an activity to your splash. I called it SplashActivity.kt
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
4 - Finally, go to you AndroidManifest.xml and add your activity splash: (Note: don't remove anything in the AndroidManifest, just add this before the Main activity).
<activity
android:name=".SplashActivity"
android:label="Kiss"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
This is done. You don't need to worry about the time that your application will demand to start, the splash will be there just for enough time. When your MainActivity is ready, it will be showed.

Categories