数据绑定类似于Windows Phone 7/.NET



在Android中,我有一个节的ArrayList(有一个Section类,所以它不仅仅是字符串的ArrayList)。我想把每个部分都表示为一个按钮。目前,我正在通过迭代每个Section,膨胀Section.xml,然后动态添加随每个特定Section而变化的属性来实现这一点:

SectionsActivity.java:

public class SectionsActivity extends Activity {
private int numSections;
LayoutInflater inflater;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sections);
numSections = App.Sections.getSectionList().size();
inflater = getLayoutInflater();
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
for (int i = 0; i < numSections; i++) {
ll.addView(getSectionButton(App.Sections.getSectionList().get(i)));
}
}
public Button getSectionButton(Section s) {
Button b = (Button) inflater.inflate(R.layout.section, null);
b.setHint("section" + s.getSectionId());
b.setText(s.getName());
b.setTextColor(Color.parseColor("#"+s.getColor()));
return b;
}
}

Sections.java:

public class Sections {
private ArrayList<Section> SectionList;
public ArrayList<Section> getSectionList() {
return SectionList;
}
public void setSectionList(ArrayList<Section> sectionList) {
SectionList = sectionList;
}
}

第.java节:

public class Section {
private String Color;
private String Name;
private int SectionId;
//constructor, standard getters and setters
}

section.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />

这很好,但我觉得可能有更好的解决方案。以下是.NET for Windows Phone 7中的一个示例:告诉XAML您想要绑定的内容(SectionList,它是一个ObservableCollection),然后为它提供一个如何表示集合中每个项的模板。

<StackPanel Name="StackPanelSection">
<ListBox Name="ListBoxSection" ItemsSource="{Binding SectionList}" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name, Converter={StaticResource StringToLowercaseConverter}}" FontFamily="Segoe WP SemiLight" FontSize="48" Foreground="{Binding HTMLColor}" Tap="TextBlockSection_Tap" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>

这样做更简单,而且如果更改SectionList的内容,UI会自动更新。我已经读了足够多关于安卓系统中数据绑定的文章,知道可能没有真正的等效方法,但完成相同任务的最佳方法是什么?有吗?即使数据绑定在这里不是一个好的解决方案,我应该用另一种方式来构建我的Android代码吗?

您在XAML中获得该绑定,因为它已烘焙到框架中。您的应用程序在支持绑定查找的运行时环境中执行,因此您可以从Microsoft获得整个绑定框架作为工具集的一部分。安卓系统就是没有这种东西。

我不知道有什么方法可以像在XAML中那样以声明性的方式进行绑定,但在类似的情况下(从WPF/.Net/XAML背景到Android),我找到了让它更方便的创造性方法。看起来你在这条路上走得很好。我为我使用的任何列表或网格使用自定义适配器,这提供了类似的便利。。。没有xaml绑定那么方便,但仍然很酷。

我还没有看到你的UI,所以我只能从你的代码中做出假设,但我只能假设你正在做的事情(LinearLayout中的按钮)可以通过ListView和自定义适配器来完成。可能最经典的安卓开发者视频是来自过去谷歌I/O的列表视图世界。它已经有几年的历史了,但仍然是一块很棒的手表,仍然很重要。

https://www.youtube.com/watch?v=wDBM6wVEO70

最新更新