6

我搜索了很多关于可观察模型和参数的信息,但我很困惑!

1-一些模型从设置器扩展BaseObservable并设置notifyChange();在设置器中,并将它们绑定到例如这样的edittext:app:addTextChangedListener="@{viewModel.getEmailTextWatcher}"并且通过更改模型的参数来notifyChange()更新文本。emailuser

2-其中一些livedata用于在方法中观察和更改 UI onChanged()。如何使用liveData和更改 UI databinding?不是通过onChanged()。什么时候onChanged()使用,而我们可以databinding用于 UI 更改?

编辑: 这是我的编码:

public class MainActivity extends AppCompatActivity implements LoginResultCallback {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    activityMainBinding.setViewModel(ViewModelProviders.of(this, new LoginViewModelFactory(this)).get(LoginViewModel.class));


}

@Override
public void onSuccess(String s) {
    Toasty.success(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}

@Override
public void onError(String s) {
    Toasty.error(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}

这是界面:

public interface LoginResultCallback {
void onSuccess(String s);
void onError(String s);
}

这是用户模型:

public class User {

@NonNull
public String mEmail;

public User(@NonNull final String email, @NonNull final String password) {
    mEmail = email;
}

@NonNull
public String getEmail() {
    return mEmail;
}

public void setEmail(@NonNull final String email) {
    mEmail = email;
}

}

这是视图模型:

public class LoginViewModel extends ViewModel {
public MutableLiveData<User> user = new MutableLiveData<>();
;
private LoginResultCallback mDataListener;

LoginViewModel(@NonNull final LoginResultCallback loginDataListener) {
    mDataListener = loginDataListener;
    if (user != null) {
          //help me fill here
    }
}

public TextWatcher getEmailTextWatcher() {
    return new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
         //help me fill here
        }
    };
}
}

这是布局:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

    <variable
        name="viewModel"
        type="com......viewmodels.LoginViewModel" />

</data>


<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="8dp"
        android:orientation="vertical">

        <EditText
            android:id="@+id/test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="test"
            android:padding="8dp"
            android:text="@{viewModel.user}" />

        <EditText
            android:id="@+id/inEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            android:inputType="textEmailAddress"
            android:padding="8dp"
            app:addTextChangedListener="@{viewModel.getEmailTextWatcher}" />


        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:onClick="@{viewModel::onLoginClicked}"
            android:text="LOGIN" />


    </LinearLayout>

</ScrollView>

我只想inEmail通过数据绑定更改edittext和上部edittext更改

4

1 回答 1

3

首先,在您的应用级别启用数据绑定,build.gradle如下所示:

android {
    ...
    dataBinding {
        enabled = true
    }
    ...
}

确保您也有lifecycle依赖项:

dependencies {
    ... 
    implementation "android.arch.lifecycle:runtime:1.1.1"
    implementation "android.arch.lifecycle:extensions:1.1.1"
    annotationProcessor "android.arch.lifecycle:compiler:$versions.lifecycle:1.1.1"
    ...
}

现在,假设您有一些User课程:

public class User {
    private String firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }
}

然后,你可以有一些UserLiveData

public class UserLiveData extends LiveData<User> {
    public UserLiveData() {
        setValue(new User());
    }
} 

这是一个简单的UserViewModel

public class UserViewModel extends ViewModel {
    private UserLiveData liveData;

    public UserViewModel() {
        liveData = new UserLiveData();
    }

    public void observeLiveDate(LifecycleOwner owner,
                                  Observer<User> observer) {
        liveData.observe(owner, observer);
    }
}

现在,activity_main.xml使用用户的名字EditText和定义布局Button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="@={user.firstName}"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/load_button"
        android:text="Load"/>

</LinearLayout>

请注意 @={user.firstName}。2 路数据绑定需要它。每次用户在 中键入内容时EditText,它也会在User对象中更新。另外,刷新 Gradle 项目,以便生成数据绑定文件。

最后,MainActivity用于ViewModel保留User对配置更改的约束。因此,您键入内容并旋转屏幕,EditText将保留文本。这是代码:

public class MainActivity extends AppCompatActivity {
    private UserViewModel viewModel;
    private ActivityMainBinding mainBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainBinding = DataBindingUtil.setContentView(this,
                R.layout.activity_main);
        mainBinding.setLifecycleOwner(this);

        viewModel = ViewModelProviders.of(this)
                .get(UserViewModel.class);

        viewModel.observeLiveDate(this, user -> {
            // set initial User object
            mainBinding.setUser(user);
        });          
        mainBinding.loadButton.setOnClickListener(v -> {
            // show the current first name 
            Toast.makeText(v.getContext(), "first name : " + mainBinding.getUser().getFirstName(), Toast.LENGTH_LONG).show();
        });
    }
}
于 2018-08-18T09:55:16.150 回答