在 Android 中,使用數據綁定庫可以簡化 Fragment 與數據之間的交互。以下是使用數據綁定庫在 Fragment 中實現數據綁定的步驟:
android {
...
dataBinding {
enabled = true
}
}
dependencies {
...
dataBinding {
implementation 'androidx.databinding:databinding-runtime:x.x.x'
annotationProcessor 'androidx.databinding:databinding-compiler:x.x.x'
}
}
請將 x.x.x
替換為最新的版本號。
<layout>
標簽,并將根布局包裝在 <layout>
標簽內。例如:<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<!-- 在這里定義要綁定的變量 -->
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- 在這里添加其他布局元素 -->
</LinearLayout>
</layout>
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import com.example.myapplication.databinding.FragmentExampleBinding;
public class ExampleFragment extends Fragment {
@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
FragmentExampleBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_example, container, false);
return binding.getRoot();
}
}
對于 Kotlin:
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.example.myapplication.databinding.FragmentExampleBinding
class ExampleFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate(inflater, R.layout.fragment_example, container, false)
return binding.root
}
}
<data>
標簽內定義要綁定的變量。例如:<data>
<variable
name="user"
type="com.example.myapplication.model.User" />
</data>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.name}" />
User user = new User("John Doe", "john.doe@example.com");
binding.setUser(user);
對于 Kotlin:
val user = User("John Doe", "john.doe@example.com")
binding.user = user
現在,當 Fragment 的視圖被創建時,數據綁定將自動將變量值應用到布局元素上。