onListItemClick () обходится для ListView с помощью специального адаптера - PullRequest
1 голос
/ 13 августа 2011

Я понимаю, что есть множество вопросов, касающихся этой проблемы, но решение установки каждого представления в row.xml на focusable = "false" и focusableInTouchMode = "false" не работает, равно как и получение ListView из ListActivity и настройка setItemsCanFocus (false).

Странно, при регистрации в контекстном меню работает длинный тап. Обычный тап хоть? Нету. Я пытался настроить слушателей, таких как OnItemClickListener, но безрезультатно.

Я где-то читал, что мог бы исправить это, переопределив getView () в моем адаптере? Я не слишком уверен, как это работает, хотя. Обратите внимание, я не хочу знать, на какой вид нажал пользователь; Мне просто важно, чтобы строка списка была нажата, чтобы инициировать соответствующий код в onListItemClick ().

Может быть, в моем файле row.xml что-то не так? Или это зависит от того, как я установил адаптер моего ListView (помещается в onResume () вместо onCreate () для обновления информации)?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  android:focusable="false"
  android:focusableInTouchMode="false">
<TextView style="?android:attr/listSeparatorTextViewStyle"
  android:id="@+id/listSectionHeader"
  android:layout_width = "fill_parent"
  android:layout_height="wrap_content"
  android:paddingTop="2dp"
  android:paddingBottom="2dp"
  android:paddingLeft="5dp"
  android:textColor="@android:color/white"
  android:visibility="gone"
  android:focusable="false"
  android:focusableInTouchMode="false"/>
<RelativeLayout
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="70dp"
  android:background="@drawable/list_button"
  android:focusable="false"
  android:focusableInTouchMode="false"
  android:clickable="true"
  android:longClickable="true"
  >
<TextView android:id="@+id/itemID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone"
    android:textStyle="bold"
    android:layout_alignParentLeft="true"
    android:focusable="false"
    android:focusableInTouchMode="false"/>
<CheckBox 
    android:id="@+id/returnedCheckbox"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_margin="10dp"
    android:checked="false"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    />
<LinearLayout
    android:layout_toRightOf="@id/returnedCheckbox"
    android:layout_margin="5dp"
    android:layout_centerVertical="true"
    android:orientation="vertical"
    android:layout_width="180dp"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false">
    <TextView 
        android:id="@+id/stuffName"
        android:layout_width="fill_parent"
        android:lines="1"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:scrollHorizontally="true"
        android:text="Hey there"
        android:textSize="25sp"
        android:textColor="#FFF"
        android:shadowColor="#000"
        android:focusable="false"
        android:focusableInTouchMode="false"
    />
    <RelativeLayout
        android:id="@+id/detailsLayout"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:focusableInTouchMode="false">
        <TextView 
            android:id="@+id/dueListItem"
            android:layout_width="wrap_content"
            android:lines="1"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:text="@string/dueListing"
            android:focusable="false"
            android:focusableInTouchMode="false"/>
        <TextView
            android:id="@+id/dueDate"
            android:layout_toRightOf="@id/dueListItem"
            android:layout_marginLeft="2dp"
            android:layout_width="90dp"
            android:lines="1"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:text="HEHEHE"
            android:focusable="false"
            android:focusableInTouchMode="false"/>
        <ImageView
            android:id="@+id/starMark"
            android:layout_alignRight="@id/detailsLayout"
            android:layout_toRightOf="@id/dueDate"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="2dp"
            android:layout_height="15dp"
            android:layout_width="15dp"
            android:scaleType="fitXY"
            android:adjustViewBounds="true"
            android:src="@drawable/list_starred"
            android:visibility="invisible"
            android:focusable="false"
            android:focusableInTouchMode="false"/>
    </RelativeLayout>
</LinearLayout>
<ImageView 
        android:id="@+id/contactPic"
        android:layout_alignParentRight="true"
        android:layout_height="48dp"
        android:layout_width="48dp"
        android:background="#FFF"
        android:layout_margin="10dp"
        android:layout_centerVertical="true"
        android:scaleType="fitCenter"
        android:padding="3dp"
        android:focusable="false"
        android:focusableInTouchMode="false"
    />
<ImageView 
        android:id="@+id/lentArrow"
        android:visibility="invisible"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/indicator_lent"
        android:layout_marginTop="42dp"
        android:layout_marginRight="1dp"
        android:focusable="false"
        android:focusableInTouchMode="false"/>
</RelativeLayout>
</LinearLayout>

Ответы [ 3 ]

1 голос
/ 13 августа 2011

Onlistitemclick никогда не будет вызываться, потому что в вашем элементе списка есть интерактивное представление. Снимите флажок и посмотрите, сможете ли вы получить клики.

Существует альтернатива использованию флажка непосредственно в макете вашего элемента. Используйте android:choiceMode="multipleChoice" для просмотра списка, если это соответствует вашим потребностям.

0 голосов
/ 14 августа 2011

Так что мне не пришлось ничего делать с моим адаптером ... onListItemClick () просто чудесным образом работал сам по себе по какой-то причине.Я сейчас чешу голову еще сильнее.Кстати, я расширил CursorAdapter, а не SimpleCursorAdatper, который, как я понимаю, немного отличается.Из того, что я прочитал, расширение CursorAdapter требует только переопределения newView () и bindView () вместо обычного getView () на основе этого http://www.workreloaded.com/2011/02/android-extending-cursoradapter-for-custom-listview/.

Anyhoo, спасибо за ответы, ребята!

0 голосов
/ 13 августа 2011

Посмотрите по этой ссылке, как создать собственный адаптер:

http://android -er.blogspot.com / 2010/06 / с использованием-convertview-в-GetView к make.html

В методе Override getView () вы можете просто установить row.setOnClickListener (), чтобы делать то, что вам нужно было делать при нажатии на этот элемент списка.

В идеале вы должны использовать convertView для заполнения класса ViewHolder, чтобы не создавать заново элементы списка, когда они уже созданы, но это другой вопрос.

Редактировать

Вот уменьшенная пользовательская реализация расширения SimpleCursorAdapter:

public class CatchCursorAdapter extends SimpleCursorAdapter {

    private final Context mContext;
    private final Cursor mCursor;
    private final int layout;
    private final LayoutInflater inflater;

    private final class ViewHolder {
        public ImageView catchImage;
        public ImageView catchStar;
        public TextView catchSpecies;
    }

    public CatchCursorAdapter(Context context, int layout, Cursor cursor) {
        super(context, layout, cursor, new String[] { }, new int[] { });

        this.mContext = context;
        this.mCursor = cursor;
        this.inflater = LayoutInflater.from(context);
        this.layout = layout;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = inflater.inflate(layout, parent, false);

            viewHolder = new ViewHolder();
            viewHolder.catchImage = (ImageView)convertView.findViewById(R.id.catch_image);
            viewHolder.catchSpecies = (TextView)convertView.findViewById(R.id.catch_species);
            viewHolder.catchStar = (ImageView)convertView.findViewById(R.id.catch_starfavorite);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder)convertView.getTag();
        }
        convertView.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Perform an action when this list item is clicked
            }
        });
        viewHolder.catchStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //You can also have buttons within your list item that can be clicked
                //independently of the parent list item.
            }
        });

        //Set the rest of your views

        return convertView;
    }
}
...