简体   繁体   中英

How to bind enabled property of Android button to ViewModel

I'm somewhat new to Android development and am now maintaining a project that uses the "android-binding" framework to utilize the MVVM pattern.

I want to disable an Android button after the user presses it, to prevent double-taps. I'd prefer to do this by binding the "enabled" property of the button to the ViewModel somehow. I'm guessing I need to use "binding:enabled" to some property but I'm not sure what the code should look like.

The xml for my Button looks like this:

<Button 
android:drawableTop="@drawable/sync_action"
android:layout_height="wrap_content" 
android:textColor="@color/title_text"
android:id="@+id/syncButton" 
style="@style/ActionButton" 
android:text="@string/syncSyncActionHeader"
binding:enabled="isSyncEnabled"
binding:onClick="beginSync"/>

And my ViewModel class looks like...

public class SyncViewModel{

   public final Command beginSync   = new Command(){

        @Override
        public void Invoke(View arg0, Object... arg1) {

            //do Sync stuff
        }
    };

   //WHAT GOES HERE?  Want to bind button's enabled property to a boolean.  
}

Please let me know what to put in the "what goes here" part of the code.

The solution to prevent double-tap of a UI button is not to disable the UI button. The solution is for the button to use an AsyncTask to perform it's duties, and check the status of that AsyncTask before allowing it to be executed again.

SyncScreen.xml

<Button 
android:id="@+id/syncButton" 
style="@style/ActionButton" 
android:text="@string/syncText"
binding:onClick="beginSync"/>

SyncViewModel.java

public class SyncViewModel
{

...

public final Command beginSync = new Command(){

    private SyncAsyncTask task;

    @Override
    public void Invoke(View arg0, Object... arg1) {

        if( task == null || task.getStatus() == Status.FINISHED )
        {
            task = new CustomAsyncTask(customParams);
            task.execute();
        }

    }
};

public class CustomAsyncTask extends AsyncTask<Void, Void, String>{
    ....
    //Irrelevant implementation details
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM