Android - элемент и подэлемент из ресурсов - PullRequest
0 голосов
/ 26 февраля 2012

Я столкнулся с проблемой, добавив вопрос к моей анкете из res / values. Поскольку мне нужен ListView, за которым следуют флажки в каждой строке, я создал собственный ListView. Это мой list_item.xml

Я удалил строки android: text = "@ string / textLarge" и "@ string / textSmall", поэтому в тегах TextView есть пустая строка.

<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp">

<TextView 
    android:id="@+id/textView_large"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:textSize="16sp">
</TextView>
<TextView 
    android:id="@+id/textView_small"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:textSize="12sp">
</TextView>
</LinearLayout>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:gravity="right">
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/checkBxc">

    </CheckBox>
</LinearLayout>
</LinearLayout>

и простой список

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView 
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>

мой файл Main.java следующий

 public class Main extends ListActivity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    setListAdapter(new MyAdapter(this,
            android.R.layout.simple_list_item_2, R.id.textView_large,
            getResources().getStringArray(R.array.questions)));
}

private class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, int resource, int textViewResourceId,
            String[] strings) {
        super(context, resource, textViewResourceId, strings);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater)          getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.list_item, parent, false);
        String[] items = getResources().getStringArray(R.array.questions);
        CheckBox chk = (CheckBox) row.findViewById(R.id.checkBxc);
        TextView txtLarge = (TextView) row.findViewById(R.id.textView_large);

        TextView txtSmall = (TextView)  row.findViewById(R.id.textView_small);

        txtLarge.setText(items[position]);
        return row;

, и он работает правильно, если я добавляю элемент из questions.xml, но отображает только 1 строку, однако мне нужно задать вопрос в виде элемента (например, «Занимаетесь ли вы чем-нибудь спортом?») И некоторыми комментариями ниже ( то есть "проверь, если сделаешь"). Как я мог это сделать?

Ответы [ 2 ]

1 голос
/ 02 марта 2012

Этот кусок:

   LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.list_item, parent, false);

не годится: вы всегда создаете новый вид элемента, даже если он уже существует, уничтожая чрезмерные объекты, что требует затрат времени.И вы можете использовать функциональность самого ArrayAdapter.Смотрите здесь .

1 голос
/ 26 февраля 2012

Вы должны создать пользовательский ArrayAdapter (класс, который расширяется от ArrayAdapter) и установить его для представления списка listView.setAdapter(yourAdapter) В этом адаптере вы должны переопределить метод getView (чтобы вернуть ваш собственный просмотр списка элементов).

См. Также этот пример: http://android -codes-examples.blogspot.com / 2011/03 / заказной-ListView-детал-selection.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...