在Android中,我有一個段的ArrayList(有一個Section類,因此它不僅僅是一個String的ArrayList)。我想將每個部分表示爲一個按鈕。像Windows Phone 7/.NET中的數據綁定?
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:目前,我通過各節迭代,充氣section.xml,然後動態地添加與每個特定部分而變化的屬性實現這個
public class Sections {
private ArrayList<Section> SectionList;
public ArrayList<Section> getSectionList() {
return SectionList;
}
public void setSectionList(ArrayList<Section> sectionList) {
SectionList = sectionList;
}
}
Section.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中的數據綁定知道可能不是真正的等價物,但是完成相同任務的最佳方式是什麼?有一個嗎?即使數據綁定在這裏不是一個好的解決方案,是否還有另外一種方法來構建我的Android代碼?