업데이트 참고 :
위의 예는 적절히 작동 해제 1.0 RC4 때문에, 고정 불필요한 가변 필요의 문제.
원래 질문 :
문서에 설명 된대로 정확히 수행하지만 작동하지 않습니다.
main.xml :
<layout xmlns:andr...
<data>
</data>
<include layout="@layout/buttons"></include>
....
buttons.xml :
<layout xmlns:andr...>
<data>
</data>
<Button
android:id="@+id/button"
...." />
MyActivity.java :
... binding = DataBindingUtil.inflate...
binding.button; ->cannot resolve symbol 'button'
버튼을 얻는 방법?
답변
문제는 포함 된 레이아웃이 데이터 바인딩 된 레이아웃으로 간주되지 않는다는 것입니다. 하나의 역할을하려면 변수를 전달해야합니다.
buttons.xml :
<layout xmlns:andr...>
<data>
<variable name="foo" type="int"/>
</data>
<Button
android:id="@+id/button"
...." />
main.xml :
<layout xmlns:andr...
...
<include layout="@layout/buttons"
android:id="@+id/buttons"
app:foo="@{1}"/>
....
그런 다음 버튼 필드를 통해 간접적으로 버튼에 액세스 할 수 있습니다.
MainBinding binding = MainBinding.inflate(getLayoutInflater());
binding.buttons.button
1.0-rc4 (방금 출시됨)부터는 더 이상 변수가 필요하지 않습니다. 다음과 같이 단순화 할 수 있습니다.
buttons.xml :
<layout xmlns:andr...>
<Button
android:id="@+id/button"
...." />
main.xml :
<layout xmlns:andr...
...
<include layout="@layout/buttons"
android:id="@+id/buttons"/>
....
답변
쉬운 완전한 예
id
포함 된 레이아웃으로 설정 하고binding.includedLayout.anyView
.
이 예제 <include
는 코드에 포함 된 뷰에 값을 전달하고 액세스 하는 데 도움이됩니다 .
1 단계
이 있습니다 . 포함 된 레이아웃 layout_common.xml
으로 전달 String
하려고합니다.
String
레이아웃에 변수를 생성 String
하고 TextView
.
<data>
// declare fields
<variable
name="passedText"
type="String"/>
</data>
<TextView
android:id="@+id/textView"
...
android:text="@{passedText}"/> //set field to your view.
2 단계
이 레이아웃을 상위 레이아웃에 포함합니다. id
포함 된 레이아웃에 제공하여 바인딩 클래스에서 사용할 수 있도록합니다. 이제 태그에 String passedText
을 전달할 수 있습니다 <include
.
activity_main.xml
<?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">
<LinearLayout
..
>
<include
android:id="@+id/includedLayout"
layout="@layout/layout_common"
app:passedText="@{@string/app_name}" // here we pass any String
/>
</LinearLayout>
</layout>
- 이제
binding.includedLayout.textView
수업에서 사용할 수 있습니다 . -
위와 같이 포함 된 레이아웃에 모든 변수를 전달할 수 있습니다.
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); binding.includedLayout.textView.setText("text");
참고 두 레이아웃 (상위 및 포함)은 모두 binding layout
,<layout
답변
이것에 대한 또 다른 흥미로운 점은 다음과 같이 바인더에서 가져온 레이아웃에 변수를 지정할 수 있다는 것입니다.
MainBinding binding = MainBinding.inflate(getLayoutInflater());
binding.buttons.setVariable(BR.varID, variable)
답변
다음과 같이 ID를 추가하기 만하면 include에서 바인딩이 작동하도록 할 수 있습니다.
<include
android:id="@+id/loading"
layout="@layout/loading_layout"
bind:booleanVisibility="@{viewModel.showLoading}" />
답변
포함 레이아웃에 대한 ID를 설정하십시오.
<include
android:id="@+id/layout"
layout="@layout/buttons" />
그때
BUTTONSBINDING binding = yourMainBinding.layout;
BUTTONSBINDING
res / layout / buttons.xml입니다.
지금 :
binding.button.setText("simple_Way");
답변
