我正在使用数据绑定应用自定义微调器。我之前从资源字符串数组传递数组,现在我从服务器获取数据,我需要将该数组放入微调器,所以我怎么能动态地做?就像这里我使用的是android:entries属性问题:如果从API中获取数据,如何更新我的微调器值?
<data>
<variable
name="model"
type="com.abc.online.viewmodels.StoreHomeViewModel" />
</data>
<Spinner
android:id="@+id/isspSelectCity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="@array/country_code_list"
android:gravity="center"
android:onItemSelected="@{(parent,view,pos,id)->model.onCitySelectItem(parent,view,pos,id)}" />
</LinearLayout>
我正在替换
android:entries="@array/country_code_list"
同
android:entries="@{model.fetchCountriesCode()}"
这是获取城市的功能
public List<String> fetchCountriesCode(){
List<String> list=new ArrayList<>();
if (getCitiesObj().getValue()!=null) {
Result[] cities = getCitiesObj().getValue().get(0).getResult();
for (Result cit : cities) {
list.add(cit.getName());
}
} return list;}
android:entries如果我们在渲染之前已经列出了值,则它会获取值,渲染后它不会采用/更新值。那我怎么能这样做?
我更喜欢使用LiveData。从文档:创建LiveData实例以保存特定类型的数据。这通常在您的ViewModel类中完成。创建一个Observer对象,该对象定义onChanged()方法,该方法控制LiveData对象保持数据更改时发生的情况。您通常在UI控制器中创建一个Observer对象,例如活动或片段。
使用observe()方法将Observer对象附加到LiveData对象。 observe()方法采用LifecycleOwner对象。这将Observer对象订阅到LiveData对象,以便通知它更改。您通常将Observer对象附加到UI控制器中,例如活动或片段。
更新存储在LiveData对象中的值时,只要附加的LifecycleOwner处于活动状态,它就会触发所有已注册的观察者。
LiveData允许UI控制器观察者订阅更新。当LiveData对象保存的数据发生更改时,UI会自动更新响应。
class Foo : ViewModel() {
...
private val mSpinnerData = MutableLiveData<List<String>>()
...
fun fetchSpinnerItems(): LiveData<List<String>> {
//fetch data
mSpinnerData.value = <some fetched list of Strings>
return mSpinnerData
}
}