处理活动初始化

时间:2018-06-25 11:53:54

标签: android android-architecture-components android-viewmodel

我有一个活动,并且在此活动中,我有一些初始化代码:

private fun init() {
        val authorFullName = photo?.user?.name ?: "?"
        val source = getString(R.string.unknown)

        photoAuthorText.text = String.format(getString(R.string.photo_by_s_on_s), authorFullName, source)

        Utils.makeUnderlineBold(photoAuthorText, arrayOf(authorFullName, source))
    }



 private fun loadPhoto() {
        Glide.with(this)
                .asBitmap()
                .load(photo?.urls?.regular)
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        photoImageView.setImageBitmap(resource)
                    }
                })
    }

然后在onCreate内部,我简单地调用:

init()
loadPhoto()

我的问题是我是否需要将此逻辑从这两种初始化方法移至ViewModel?我认为将这种逻辑保留在Activity中不是一个好主意。

我了解DataBinding,但是我不想使用它。还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

签入Java

活动代码 公共类UserProfileActivity扩展了Activity {      UserProfileModel viewModel;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.user_activity_layout);
     viewModel = ViewModelProviders.of(this).get(UserProfileModel.class);
     bindData();        

 }

void bindData() {
    viewModel.userLiveData.observer(this, new Observer() {
        @Override
         public void onChanged(@Nullable UserFullDetails data) {
             // update ui.
             // You can set Profile Image And User Details UI Components
         }
     });
}

}

此ViewModel代码

public class UserProfileModel extends ViewModel {
     private MediatorLiveData<UserFullDetails> userFullDetails;
     public UserModel() {

     }

     public LiveData<UserFullDetails> getUserFullDetails() {
        if (userFullDetails == null) {
            userFullDetails = new MediatorLiveData<>();
            getUpdatedUserData();
        }
        return userFullDetails;
    }

    void getUpdatedUserData() {
        LocalData<UserFullDetails> mResponse = getDataFromDataSource(); //Data come from local or cloud
        userFullDetails.setValue(mResponse.getData());
    }
 }