Android: onItemClick и onItemLongClick не отвечают - PullRequest
0 голосов
/ 01 июня 2018

Мое приложение для Android состоит из базы данных SQLite, которая заполняет отдельные элементы ListView данными, сохраненными пользователем.Эти предметы доступны для отображения в activity_main.xml.У меня есть класс с именем RecordsListFragment, который содержит два проблемных метода: onItemClick и onItemLongClick.Вот класс целиком:

package com.example.benignfella.projectworkinghoursapplication.Fragment;

import android.app.Activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.example.benignfella.projectworkinghoursapplication.R;
import com.example.benignfella.projectworkinghoursapplication.Adapter.RecordsListAdapter;
import com.example.benignfella.projectworkinghoursapplication.Database.RecordsDAO;
import com.example.benignfella.projectworkinghoursapplication.GetSet.Records;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class RecordsListFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener {

    public static final String ARGUMENT_ITEM_ID = "records_list";

    Activity activity;
    ListView recordsListView;
    ArrayList<Records> records;

    RecordsListAdapter recordsListAdapter;
    RecordsDAO recordsDAO;

    private GetRecordsTask task;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    activity = getActivity();
    recordsDAO = new RecordsDAO(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_records_list, container, false);
    findViewsById(view);

    task = new GetRecordsTask(activity);
    task.execute((Void) null);
    return view;
    }

    private void findViewsById(View view) {
    recordsListView = (ListView) view.findViewById(R.id.list_records);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Records record = (Records) parent.getItemAtPosition(position);

    if (records != null) {
        Bundle arguments = new Bundle();
        arguments.putParcelable("selectedRecord,", record);

        CustomRecordsDialogFragment customRecordsDialogFragment = new CustomRecordsDialogFragment();
        customRecordsDialogFragment.setArguments(arguments);
        customRecordsDialogFragment.show(getFragmentManager(), CustomRecordsDialogFragment.ARGUMENT_ITEM_ID);
    }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    Records records = (Records) parent.getItemAtPosition(position);

    recordsDAO.deleteRecord(records);
    recordsListAdapter.remove(records);

    return true;
    }


    public class GetRecordsTask extends AsyncTask<Void, Void, ArrayList<Records>> {

    private final WeakReference<Activity> activityWeakRef;

    public GetRecordsTask(Activity context) {
        this.activityWeakRef = new WeakReference<Activity>(context);
    }

    @Override
    protected ArrayList<Records> doInBackground(Void... arg0) {
        ArrayList<Records> recordsArrayList = recordsDAO.getRecords();
        return recordsArrayList;
    }

    @Override
    protected void onPostExecute(ArrayList<Records> empList) {
        if (activityWeakRef.get() != null && !activityWeakRef.get().isFinishing()) {
            records = empList;
            if (empList != null) {
                if (empList.size() != 0) {
                    recordsListAdapter = new RecordsListAdapter(activity, empList);
                    recordsListView.setAdapter(recordsListAdapter);
                } else {
                    Toast.makeText(activity, "No Records about records... wait wot m8?",
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    }

    public void updateView() {
    task = new GetRecordsTask(activity);
    task.execute((Void) null);
    }

    public void onResume() {
    getActivity().setTitle(R.string.app_name);
    getActivity().getActionBar().setTitle(R.string.app_name);
    super.onResume();
    }
}

Вот activity_main.xml с FrameLayout:

<RelativeLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</RelativeLayout>

Файл ресурсов макета, содержащий ListView, называется fragment_records_list.xmlи вот оно:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f9f9f9">

    <ListView
    android:id="@+id/list_records"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:dividerHeight="10dp"
    android:drawSelectorOnTop="true"
    android:footerDividersEnabled="false"
    android:padding="10dp"
    android:scrollbarStyle="outsideOverlay"/>

</RelativeLayout>

Наконец, есть файл ресурсов, содержащий макет одного элемента, list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed"
    android:descendantFocusability="blocksDescendants">

    <RelativeLayout
    android:id="@+id/layout_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/text_record_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="ID"
        android:textSize="20dp"/>

    <TextView
        android:id="@+id/text_record_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/text_record_id"
        android:padding="5dp"
        android:text="Date"
        android:textColor="#00942b"
        android:textSize="20dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/text_record_date"
        android:drawableStart="@drawable/ic_date_range_black_24dp"
        android:padding="5dp"
        />

    <TextView
        android:id="@+id/text_record_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text_record_id"
        android:padding="5dp"
        android:text="Description"
        />

    <TextView
        android:id="@+id/text_record_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text_record_description"
        android:padding="5dp"
        android:text="17:00"
        android:textSize="16dp"
        android:textColor="#004561"
        />

    <TextView
        android:id="@+id/text_record_dash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text_record_description"
        android:layout_toRightOf="@id/text_record_start"
        android:padding="5dp"
        android:text="-"
        android:textSize="16dp"
        />

    <TextView
        android:id="@+id/text_record_finish"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text_record_description"
        android:layout_toRightOf="@id/text_record_dash"
        android:padding="5dp"
        android:text="20:00"
        android:textSize="16dp"
        android:textColor="#c7002a"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_below="@id/text_record_description"
        android:layout_toRightOf="@id/text_record_finish"
        android:drawableStart="@drawable/ic_timer_black_24dp"
       />
    </RelativeLayout>

    <View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_below="@id/layout_item"
    android:background="#000000"
    />

</RelativeLayout>

Я не нашел определенного ответана мой вопрос, поэтому я прошу немного помощи здесь.

1 Ответ

0 голосов
/ 01 июня 2018

Вам нужно установить OnItemClickListener и OnLongItemClickListener на ListView, я отредактировал ваш метод в переменной инициализации ListView:

private void findViewsById(View view) {
    recordsListView = (ListView) view.findViewById(R.id.list_records);
    recordsListView.setOnItemClickListener(this);
    recordsListView.setOnItemLongClickListener(this);
}
...