【问题标题】:How to bind enabled property of Android button to ViewModel如何将 Android 按钮的启用属性绑定到 ViewModel
【发布时间】:2013-10-01 18:49:03
【问题描述】:

我对 Android 开发有点陌生,现在我正在维护一个使用“android-binding”框架来利用 MVVM 模式的项目。

我想在用户按下 Android 按钮后禁用它,以防止双击。我宁愿通过将按钮的“启用”属性以某种方式绑定到 ViewModel 来做到这一点。我猜我需要对某些属性使用“绑定:启用”,但我不确定代码应该是什么样子。

我的 Button 的 xml 如下所示:

<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"/>

我的 ViewModel 类看起来像......

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.  
}

请让我知道在代码的“这里发生了什么”部分中添加了什么。

【问题讨论】:

    标签: java android button binding viewmodel


    【解决方案1】:

    防止双击 UI 按钮的解决方案不是禁用 UI 按钮。解决方案是让按钮使用 AsyncTask 来执行其职责,并在允许再次执行之前检查该 AsyncTask 的状态。

    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
        ....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 2011-08-26
      • 1970-01-01
      • 2015-11-24
      • 2011-08-01
      相关资源
      最近更新 更多