سؤال

I am using a DrawerLayout for navigation, which includes a ListView populated by strings stored in XML. Initializing the ListView looks as follows:

mDrawerListView.setAdapter(new ArrayAdapter<String>(
  getActionBar().getThemedContext(),
  android.R.layout.simple_list_item_activated_1,
  android.R.id.text1,
  getResources().getStringArray(R.array.navigation_section_titles)
));

Converting this view to XML currently looks like the following:

<ListView
  android:id="@+id/navigation_drawer"
  android:background="#cccc"
  android:entries="@array/navigation_section_titles"
  android:choiceMode="singleChoice"
  android:divider="@android:color/transparent"
  android:dividerHeight="0dp"
  android:layout_gravity="start"
  android:layout_height="match_parent"
  android:layout_width="@dimen/navigation_drawer_width"
  tools:layout="@layout/simple_list_item_activated_1"/>

The appearance of the ListView is not consistent between the two forms. That requires setting the adapter with the android resources, as seen in the first block. Is it possible to set the adapter without having to redefine the list of strings to use in the list? Better yet, is it possible to define this styling and list content entirely within XML?

هل كانت مفيدة؟

المحلول

ListViews cant' be entirely define in XML. There are 2 key parts to it, however, that can be defined in XML, plus the footer and header if you so choose. All 4 of these can be defined in XML, but the relationship between them must be defined in code. In theory these could be combined, and in fact are done so in ListPreferences, but the standard Android context doesn't allow for that.

So, the 4 parts that can be defined in XML are:

  1. ListView- Contains location, size, dividers, and background
  2. Adapter View- Shows what a single row looks like
  3. Header- This is a custom first row in your list
  4. Footer- This is a custom last row of your list

All of these, for better or worse, are connected at runtime. The adapter controls the flow between them. The code you have is the best wa that can be done, unfortunately the XML simply isn't sufficient to completely define the ListView in XML.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top