データバインディングを使用してビューを更新する方法を理解していません。私はトグルスイッチがボタンを表示/非表示にする実験を行っています。レイアウト要素のデータバインディングでの可視性を更新する方法
期待される動作:
トグルボタンが(すなわちVISIBLE
またはGONE
)のオン/「キーの追加」ボタンを切り替える必要があります。
実際の動作:
[キーの追加]ボタンの表示は更新されません。レイアウトがロードされるときに一度だけ設定されます。ここで
は、レイアウトファイルです:トグルボタンが押された場合
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="mainActivity"
type="tanager.sandbox.MainActivity" />
<variable
name="businessLogic"
type="tanager.sandbox.BusinessLogic" />
</data>
<RelativeLayout
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="tanager.sandbox.MainActivity">
<LinearLayout
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/add_key_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="@{businessLogic.getVisible()}"
android:text="@string/add_key" />
</LinearLayout>
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/linear_layout"
android:layout_weight="3"
android:text="ToggleButton"
android:onClick="@{() -> mainActivity.click()}"/>
</RelativeLayout>
</layout>
、それはビジネスロジックに値を切り替え主な活動、上のメソッドを呼び出します。私はadd_key_button
がトグルボタンが押されたときに自動的に可視性を更新することを期待しています。 、私は少しあなたのコードをリファクタリング
public class BusinessLogic extends BaseObservable {
private boolean visible;
public BusinessLogic(){
visible = true;
}
public void toggleVisibility(){
visible = !visible;
notifyPropertyChanged(BR.visible);
}
@Bindable
public int getVisible(){
return visible? View.VISIBLE:View.GONE;
}
}