Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/disable an activity programmatically

I have an activity in in my app which I have kept as

android:enabled="false"

now I want that when a button is clicked it should get changer to

android:enabled="true"

How can I do this?

like image 250
vishalmullur Avatar asked Jul 05 '13 17:07

vishalmullur


People also ask

How to disable activity in Android Studio?

Use PackageManager and setComponentEnabledSetting() to enable or disable any component within your app: activity, service, etc.

What is the use of activity tag?

activity is the subelement of application and represents an activity that must be defined in the AndroidManifest. xml file. It has many attributes such as label, name, theme, launchMode etc. android:label represents a label i.e. displayed on the screen.

How do I change launcher activity in android programmatically?

The easiest way is to make MainActivity launcher activity, as usual. Then check in MainActivity#onCreate(Bundle) via SharedPreferences if the user already logged in and, if not, start LoginActivity immediately.


3 Answers

Use PackageManager and setComponentEnabledSetting() to enable or disable any component within your app: activity, service, etc.

like image 162
CommonsWare Avatar answered Oct 04 '22 17:10

CommonsWare


Here's an example how to enable/disable an Activity:

    PackageManager pm = getPackageManager(); 
    pm.setComponentEnabledSetting(new ComponentName(this, com.packagename.MyActivity.class),
                                  PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

    pm.setComponentEnabledSetting(new ComponentName(this, com.packagename.MyActivity.class),
                                  PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
like image 32
Emanuel Moecklin Avatar answered Oct 04 '22 19:10

Emanuel Moecklin


Here's a nice way to do it:

  public static void setActivityEnabled(Context context,final Class<? extends Activity> activityClass,final boolean enable)
    {
    final PackageManager pm=context.getPackageManager();
    final int enableFlag=enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
    pm.setComponentEnabledSetting(new ComponentName(context,activityClass),enableFlag,PackageManager.DONT_KILL_APP);
    }

example usage:

setActivityEnabled(this,SomeActivity.class,false);
like image 45
android developer Avatar answered Oct 04 '22 19:10

android developer