0
我很難理解如何使用數據綁定來更新視圖。我正在試驗一個簡單的例子,其中一個切換開關將使按鈕在視圖中出現/消失。如何使用數據綁定更新佈局元素的可見性
預期的行爲:
的切換按鈕應可以切換上(即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
在按下切換按鈕時自動更新其可見性。這裏是MainActivity
:
public class MainActivity extends AppCompatActivity {
private BusinessLogic _businessLogic;
@Override
protected void onCreate(Bundle savedInstanceState) {
_businessLogic = new BusinessLogic();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this,
R.layout.activity_main);
binding.setMainActivity(this);
binding.setBusinessLogic(_businessLogic);
}
public void click() {
_businessLogic.toggleVisibility();
}
}
,這裏是業務邏輯類:
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;
}
}