数据绑定
implementation 'androidx.databinding:databinding-runtime:7.0.0'android { ... buildFeatures { dataBinding true } }public class MyViewModel extends ViewModel { private final MutableLiveData<String> message = new MutableLiveData<>(); public LiveData<String> getMessage() { return message; } public void setMessage(String msg) { message.setValue(msg); } }<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="viewModel" type="com.example.MyViewModel" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{viewModel.message}" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{() -> viewModel.setMessage('Hello World!')}" android:text="Update Message" /> </LinearLayout> </layout>public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class); binding.setViewModel(viewModel); binding.setLifecycleOwner(this); } }
2. Jetpack Compose
小结
Last updated