Я не могу найти способ выбрать элементы из списка, каждый из которых состоит из трех текстовых полей [дубликаты]

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

В моей деятельности у меня есть четыре onClickListeners, которые отлично работают и связаны с четырьмя кнопками в верхней части моего макета. Проблема возникает, когда, кроме того, я пытаюсь установить onItemClickListener для элементов ListView в нижней части того же макета. Каждый элемент этого ListView состоит из трех текстовых представлений, и я написал для них специальный адаптер. Они отображаются отлично, но когда я нажимаю на них, ничего не происходит (инструкции onItemClick никогда не достигаются).

Это макет, проблема с "ingredients_list_view" ближе к концу: (кстати, самый последний элемент, @android:id/list, есть только потому, что в противном случае я получаю ошибку компиляции в своей деятельности, я пока не разобрался почему - а то он мне и не нужен, и показывать и вообще ничего не должен)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_recipe_name"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextTitle"
        android:layout_gravity="top"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_servings"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextServings"
        android:layout_gravity="top"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_cake_size"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextSize"
        android:layout_gravity="top"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/btnEditDelete"
            android:orientation="horizontal">

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_edit"
                android:id="@+id/btnEdit"/>

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_delete"
                android:id="@+id/btnDelete"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0"
            android:id="@+id/btnSaveCancel"
            android:orientation="horizontal">

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_save"
                android:id="@+id/btnSave"/>

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_cancel"
                android:id="@+id/btnCancel"/>

        </LinearLayout>
    </LinearLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ingredients_list_view"
        android:divider="#48C"
        android:dividerHeight="1dp"
        android:layout_weight="1" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:id="@android:id/list"/>

</LinearLayout>

Это макет для каждого элемента listView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/ingredient_list_item"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
    <EditText
        android:id="@+id/quantity_list_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
    <EditText
        android:id="@+id/unit_list_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
</LinearLayout>

... и это соответствующие разделы основной деятельности:


public class Recipe extends ListActivity implements View.OnClickListener {

    public static final String TABLE = "Recipes";

    public static final String KEY_ID = "recipeID";
    public static final String KEY_title = "title";
    public static final String KEY_servings = "servings";
    public static final String KEY_size = "size";

    public int recipeID;
    public String title;
    public String servings;
    public String size;

    Button btnEdit, btnDelete, btnSave, btnCancel;
    LinearLayout btnEditDelete, btnSaveCancel;
    EditText editTextTitle;
    EditText editTextServings;
    EditText editTextSize;

    int _Recipe_Id;
    int editMode;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_view);
        redraw();
    }

    @Override
    public void onClick(View view) {
// These work perfectly fine (except for the last one)
        RecipeDBOps repo = new RecipeDBOps(this);
        ArrayList<HashMap<String, String>> recipeList = repo.getRecipeList(); // so far not used
        if (view == findViewById(R.id.btnDelete)) {
            MixDBOps.delete(_Recipe_Id);
            RecipeDBOps.delete(_Recipe_Id);
            finish();
        }
        else if (view == findViewById(R.id.btnEdit)) { // Changes the fields to "editable" and switches button
            setEditMode();
        }
        else if (view == findViewById(R.id.btnCancel)) {
            finish();
        }
        else if (view == findViewById(R.id.btnSave)){
            Recipe recipe = RecipeDBOps.getRecipeById(_Recipe_Id);
            recipe.title = editTextTitle.getText().toString();
            recipe.servings = editTextServings.getText().toString();
            recipe.size = editTextSize.getText().toString();
            RecipeDBOps.update (recipe);
            finish();
        }
        else if (view == findViewById(R.id.ingredients_list_view)){
            System.out.println("OK2"); // Tried, but doesn't work
        }
    }

    public void setWeight (LinearLayout ll, LinearLayout.LayoutParams visibility){...}

    public void setReadOnlyMode(){...}

    public void setEditMode(){...}

    public void redraw(){
        editTextTitle = (EditText) findViewById(R.id.editTextTitle);
        editTextServings = (EditText) findViewById(R.id.editTextServings);
        editTextSize = (EditText) findViewById(R.id.editTextSize);
        btnEdit = (Button) findViewById(R.id.btnEdit);
        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnSave = (Button) findViewById(R.id.btnSave);
        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnEditDelete = (LinearLayout) findViewById(R.id.btnEditDelete);
        btnSaveCancel = (LinearLayout) findViewById(R.id.btnSaveCancel);

        setReadOnlyMode();

        //
        // Populate recipe fields
        //
        Intent intent = getIntent();
        _Recipe_Id = intent.getIntExtra("recipe_ID", 0);
        editMode = intent.getIntExtra("editMode", 0);
        RecipeDBOps repo = new RecipeDBOps(this);
        Recipe recipe;
        recipe = repo.getRecipeById(_Recipe_Id);

        if (recipe.title != null) {
            editTextTitle.setText(recipe.title);
            editTextServings.setText(recipe.servings);
            editTextSize.setText(recipe.size);
        }

        //
        // Populate recipe and ingredient fields
        //
        ArrayList<Entry> arrayOfEntries = new ArrayList<Entry>();
        EntryAdapter adapter = new EntryAdapter(this, arrayOfEntries);
        ListView listView = (ListView) findViewById(R.id.ingredients_list_view);
        listView.setAdapter(adapter);
////////////////////////////////////////////////////////////////////////////////////
        // This is the part that does not work
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ListView clickedObj = (ListView) parent.getItemAtPosition(position);
            // Once I am able to activate this onItemClick I will write the rest of the code to deal with clickdObj 
            System.out.println("OK1");
        }});
////////////////////////////////////////////////////////////////////////////////////


        HashMap<String, String> h;
        MixDBOps repoMix = new MixDBOps(this); // repo represents the DB
        ArrayList<HashMap<String, String>> entryList = repoMix.getMixById(_Recipe_Id); // recipeList is the output of the SQL query
        Entry[] ent = new Entry[entryList.size()];

        for (int i = 0; i < entryList.size(); i++) {
            h = entryList.get(i);
            ent[i] = new Entry();
            ent[i].recipe_name = recipe.title;
            ent[i].ingredient_name = h.get("ingredient_name"); // temporarily replaced by spinner
            ent[i].quantity= Integer.parseInt(h.get("quantity"));
            ent[i].unit_name= h.get("unit_name");
            adapter.add(ent[i]);
        }

        btnEdit = (Button) findViewById(R.id.btnEdit);
        btnEdit.setOnClickListener(this);

        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(this);

        btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);

        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(this);

        if (editMode == 1){
            setEditMode();
        }
    }
}

Кто-нибудь может мне помочь?


person Bob-it    schedule 17.02.2020    source источник
comment
Об элементе с @android:id/list: это происходит потому, что ваша активность наследуется от ListActivity. Поскольку вы предоставляете свой собственный макет, ваша активность может наследоваться непосредственно от AppCompatActivity.   -  person Bö macht Blau    schedule 17.02.2020


Ответы (1)


добавить два атрибута в каждый текст редактирования элемента списка

    android:focusable="false"
    android:clickable="false"
person SINA    schedule 17.02.2020
comment
Только что попробовал, но они, кажется, не имеют никакого значения - person Bob-it; 18.02.2020
comment
я думаю, что эта проблема возникает из-за того, что когда вы щелкаете в представлении списка, представление списка не распознает ваш щелчок. пожалуйста, проверьте, когда вы щелкаете элемент списка, видите ли вы какой-либо эффект в представлении списка, который показывает, что вы щелкаете элемент. например, когда вы нажимаете элемент, элемент показывает небольшую анимацию. - person SINA; 18.02.2020
comment
На самом деле нет никакого признака того, что мой щелчок распознан - person Bob-it; 18.02.2020
comment
в своем вопросе вы говорите, что каждый элемент этого ListView состоит из трех текстовых представлений, но в вашем коде вы добавляете три текста редактирования. - person SINA; 18.02.2020
comment
Да, вы правы, я пробовал с обоими. Фактически, это должны быть EditText, которые программно включаются или отключаются (т. е. вы нажимаете на редактирование, и тексты становятся редактируемыми). Тем не менее, моя идея заключается в том, что я нажимаю на что-то в одной строке (три текстовых элемента, принадлежащие одной и той же записи ListView), и щелчок запускается, но этого не происходит. - person Bob-it; 18.02.2020
comment
когда вы щелкаете элемент представления списка, на самом деле вы фокусируетесь на редактировании текста, а представление списка не распознает ваш щелчок. также вы можете использовать эту ссылку - person SINA; 18.02.2020
comment
В конце концов я смог заставить его работать. Мой первоначальный код был в порядке, но фокусируемость и кликабельность изменили ситуацию. - person Bob-it; 19.02.2020