Android には、セクションの ArrayList があります (セクション クラスがあるため、単なる文字列の ArrayList ではありません)。各セクションをボタンとして表現したいと思います。現在、各セクションを反復処理し、section.xml を膨らませてから、特定のセクションごとに異なるプロパティを動的に追加することで、これを実現しています。
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;
}
}
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" />
これはうまくいきますが、おそらくもっと良い解決策があると思います。Windows Phone 7 の .NET の例を次に示します。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 コードを構築する別の方法はありますか?