简体   繁体   English

Android:OnItemCLickListener无法在listview中运行

[英]Android: OnItemCLickListener not working in listview

I'm relatively new to Android development but my project was all going fairly well until I hit this problem. 我对Android开发相对较新,但我的项目进展顺利,直到遇到这个问题。 I have researched this question but none of the solutions to other questions have fixed my problem. 我已经研究过这个问题,但其他问题的解决方案都没有解决我的问题。

I have a SportsAvtivity which implements AdapterView OnItemClickListener but nothing is happening when I click on a list item. 我有一个SportsAvtivity ,它实现了AdapterView OnItemClickListener但是当我点击列表项时没有发生任何事情。

Any Help would be greatly appreciated. 任何帮助将不胜感激。

SportsActivity.java: SportsActivity.java:

public class SportsActivity  extends Activity implements           AdapterView.OnItemClickListener {


ListView mainListView;
JSONAdapter mJSONAdapter;



private static final String QUERY_URL = "http://myurl.myurl/jsonOutput.php";
ProgressDialog mDialog;

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

    // Access the ListView
    mainListView = (ListView) findViewById(R.id.list);

    // Set this activity to react to list items being pressed
    mainListView.setOnItemClickListener(this);

    // Create a JSONAdapter for the ListView
    mJSONAdapter = new JSONAdapter(this, getLayoutInflater());

    // Set the ListView to use the ArrayAdapter
    mainListView.setAdapter(mJSONAdapter);

    mDialog = new ProgressDialog(this);
    mDialog.setMessage("Searching for Clubs");
    mDialog.setCancelable(false);

    // Create a client to perform networking
    AsyncHttpClient client = new AsyncHttpClient();

    // Show ProgressDialog to inform user that a task in the background is  occurring
    mDialog.show();

            // Have the client get a JSONArray of data
    // and define how to respond
    client.get(QUERY_URL, new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(JSONObject jsonObject) {

                    // Dismiss the ProgressDialog
                    mDialog.dismiss();

                    // update the data in your custom method.
                     mJSONAdapter.updateData(jsonObject.optJSONArray("vfss"));
                }

                @Override
                public void onFailure(int statusCode, Throwable throwable, JSONObject error) {

                    // Dismiss the ProgressDialog
                    mDialog.dismiss();

                    // Display a "Toast" message
                    // to announce the failure
                    Toast.makeText(getApplicationContext(), "Network error, please close app and try again", Toast.LENGTH_LONG).show();

                    // Log error message
                    // to help solve any problems
                    Log.e("omg android", statusCode + " " + throwable.getMessage());
                }
            }
    );

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    // Now that the user's chosen an item, grab the cover data
    //JSONObject jsonObject = (JSONObject) mJSONAdapter.getItem(position);
    //String clubImage = jsonObject.optString("Image_Path","");

    Toast.makeText(SportsActivity.this,"Clicked",Toast.LENGTH_SHORT).show();

    // create an Intent to take you over to a new DetailActivity
    Intent clubIntent = new Intent(this, ClubActivity.class);

    // pack away the data about the cover
    // into your Intent before you head out
    //clubIntent.putExtra("clubImage", clubImage);

    // start the next Activity using your prepared Intent
    startActivity(clubIntent);
}

}

activity_sports.xml: activity_sports.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#F1F1F1"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:listitem="@layout/row">

</ListView>

</LinearLayout>

row.xml: row.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical"
android:background="#ffffffff"
android:descendantFocusability="blocksDescendants">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:orientation="horizontal"
    android:showDividers="none"
    android:focusable="false"
    android:clickable="false">

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:src="@mipmap/sports256"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="2dp"
        android:focusable="false"
        android:clickable="false"/>



        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/clubName"
            android:layout_weight="0.7"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:textColor="#ff000000"
            android:textSize="25sp"
            android:maxWidth="80dp"
            android:minWidth="80dp"
            android:focusable="false"
            android:clickable="false"/>

        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:src="@mipmap/point"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:layout_weight="0.1"
            android:focusable="false"
            android:clickable="false"/>



</LinearLayout>

</LinearLayout>

logcat when I click an item: 单击一个项目时的logcat:

05-22 22:40:20.851    6628-6628/dmca.vfss I/libpersona﹕ KNOX_SDCARD checking this for 10340
05-22 22:40:20.851    6628-6628/dmca.vfss I/libpersona﹕ KNOX_SDCARD not a persona
05-22 22:40:37.531    6628-6628/dmca.vfss V/ActivityThread﹕ updateVisibility : ActivityRecord{22ae818d token=android.os.BinderProxy@28038da6 {dmca.vfss/dmca.vfss.MainActivity}} show : false
05-22 22:40:20.851    6628-6628/dmca.vfss E/Zygote﹕ MountEmulatedStorage()
05-22 22:40:20.851    6628-6628/dmca.vfss E/Zygote﹕ v2
05-22 22:40:20.931    6628-6628/dmca.vfss I/SELinux﹕ Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_SM-N9005_4.4.2 ver=40
05-22 22:40:20.931    6628-6628/dmca.vfss I/SELinux﹕ Function: selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_SM-N9005_5.0_0002
05-22 22:40:20.931    6628-6628/dmca.vfss E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
05-22 22:40:20.931    6628-6628/dmca.vfss I/art﹕ Late-enabling -Xcheck:jni
05-22 22:40:20.971    6628-6628/dmca.vfss D/TimaKeyStoreProvider﹕ TimaSignature is unavailable
05-22 22:40:20.971    6628-6628/dmca.vfss D/ActivityThread﹕ Added TimaKeyStore provider
05-22 22:40:21.021    6628-6628/dmca.vfss D/ResourcesManager﹕ creating new AssetManager and set to /data/app/dmca.vfss-1/base.apk
05-22 22:40:21.161    6628-6628/dmca.vfss D/Activity﹕ performCreate Call secproduct feature valuefalse
05-22 22:40:21.161    6628-6628/dmca.vfss D/Activity﹕ performCreate Call debug elastic valuetrue
05-22 22:40:21.181    6628-6653/dmca.vfss D/OpenGLRenderer﹕ Render dirty regions requested: true
05-22 22:40:21.191    6628-6628/dmca.vfss D/Atlas﹕ Validating map...
05-22 22:40:21.211    6628-6653/dmca.vfss I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1_RB1.05.00.00.002.025_msm8974_LA.BF.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.01.03
Build Date: 11/19/14 Wed
Local Branch: mybranch5813579
Remote Branch: quic/LA.BF.1.1_rb1.11
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1_RB1.05.00.00.002.025 + 30e7589 +  NOTHING
05-22 22:40:21.211    6628-6653/dmca.vfss I/OpenGLRenderer﹕ Initialized EGL, version 1.4
05-22 22:40:21.241    6628-6653/dmca.vfss I/OpenGLRenderer﹕ HWUI protection enabled for context ,  &this =0xaef22088 ,&mEglDisplay = 1 , &mEglConfig = 8
05-22 22:40:21.251    6628-6653/dmca.vfss D/OpenGLRenderer﹕ Enabling debug mode 0
05-22 22:40:21.331    6628-6628/dmca.vfss I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@28038da6 time:398511238
05-22 22:40:36.701    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:36.851    6628-6628/dmca.vfss I/Timeline﹕ Timeline: Activity_launch_request id:dmca.vfss time:398526750
05-22 22:40:36.911    6628-6628/dmca.vfss D/AbsListView﹕ Get MotionRecognitionManager
05-22 22:40:36.971    6628-6628/dmca.vfss D/Activity﹕ performCreate Call secproduct feature valuefalse
05-22 22:40:36.971    6628-6628/dmca.vfss D/Activity﹕ performCreate Call debug elastic valuetrue
05-22 22:40:36.971    6628-7916/dmca.vfss I/System.out﹕ Thread-187779(ApacheHTTPLog):Reading from variable values from setDefaultValuesToVariables
05-22 22:40:36.981    6628-7916/dmca.vfss I/System.out﹕ Thread-187779(ApacheHTTPLog):isShipBuild true
05-22 22:40:36.981    6628-7916/dmca.vfss I/System.out﹕ Thread-187779(ApacheHTTPLog):SmartBonding Enabling is true, SHIP_BUILD is true, log to file is false, DBG is false
05-22 22:40:37.181    6628-6628/dmca.vfss I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@108d0db6 time:398527086
05-22 22:40:43.041    6628-7916/dmca.vfss I/System.out﹕ pool-1-thread-1 calls detatch()
05-22 22:40:43.081    6628-6628/dmca.vfss W/Settings﹕ Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
05-22 22:40:43.111    6628-8487/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.111    6628-8485/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.111    6628-8485/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isShipBuild true
05-22 22:40:43.111    6628-8487/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isShipBuild true
05-22 22:40:43.111    6628-8487/dmca.vfss I/System.out﹕ (HTTPLog)-Thread-187787-964167417: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
05-22 22:40:43.111    6628-8487/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.111    6628-8485/dmca.vfss I/System.out﹕ (HTTPLog)-Thread-187785-202010435: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
05-22 22:40:43.111    6628-8485/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.121    6628-8486/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.121    6628-8486/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isShipBuild true
05-22 22:40:43.121    6628-8486/dmca.vfss I/System.out﹕ (HTTPLog)-Thread-187786-522844608: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
05-22 22:40:43.121    6628-8486/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.131    6628-6628/dmca.vfss E/ViewRootImpl﹕ sendUserActionEvent() mView == null
05-22 22:40:43.151    6628-8487/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.151    6628-8485/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.151    6628-8486/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:43.161    6628-8487/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:44.231    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:44.911    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:45.451    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:45.681    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:45.971    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:46.291    6628-8485/dmca.vfss I/System.out﹕ (HTTPLog)-Static: isSBSettingEnabled false
05-22 22:40:46.521    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:46.751    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:46.961    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:40:47.141    6628-6628/dmca.vfss D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-22 22:41:47.261    6628-6628/dmca.vfss V/ActivityThread﹕ updateVisibility : ActivityRecord{1f9e9c31 token=android.os.BinderProxy@108d0db6 {dmca.vfss/dmca.vfss.SportsActivity}} show : true
05-22 22:42:46.921    6628-6635/dmca.vfss W/art﹕ Suspending all threads took: 6.217ms
05-22 22:48:56.991    6628-6635/dmca.vfss W/art﹕ Suspending all threads took: 8.950ms

JSONAdapter.java: JSONAdapter.java:

package dmca.vfss;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONObject;


public class JSONAdapter extends BaseAdapter {

Context mContext;
LayoutInflater mInflater;
JSONArray mJsonArray;

public JSONAdapter(Context context, LayoutInflater inflater) {
    mContext = context;
    mInflater = inflater;
    mJsonArray = new JSONArray();
}

@Override
public boolean isEnabled (int position) {
    return false;
}



@Override
public int getCount() {
    return mJsonArray.length();
}

@Override
public Object getItem(int position) {
    return mJsonArray.optJSONObject(position);
}

@Override
public long getItemId(int position) {
    // unused
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    // check if the view already exists
    // if so, no need to inflate and findViewById again!
    if (convertView == null) {

        // Inflate the custom row layout from your XML.
        convertView = mInflater.inflate(R.layout.row, null);

        // create a new "Holder" with subviews
        holder = new ViewHolder();
        holder.thumbnailImageView = (ImageView) convertView.findViewById(R.id.ivImage);
        holder.titleTextView = (TextView) convertView.findViewById(R.id.tvName);


        // hang onto this holder for future recycling
        convertView.setTag(holder);
    } else {


        // just get the holder you already made
        holder = (ViewHolder) convertView.getTag();
    }

    // Get the current data in JSON form
    JSONObject jsonObject = (JSONObject) getItem(position);

    // See if there is an image path in the Object
    if (jsonObject.has("Image_Path")) {



        // Construct the image URL (specific to API)
        String imageURL = jsonObject.optString("Image_Path");

        // Use Picasso to load the image
        // Temporarily have a placeholder in case it's slow to load
        Picasso.with(mContext).load(imageURL).into(holder.thumbnailImageView);
    } else {

        // If there is no cover ID in the object, use a placeholder
        holder.thumbnailImageView.setImageResource(R.mipmap.sports256);
    }

    // Grab the club name from the JSON
    String clubName = "";


    if (jsonObject.has("Club_Name")) {
        clubName = jsonObject.optString("Club_Name");
    }



    // Send the String to the TextView for display
    holder.titleTextView.setText(clubName);



    return convertView;
}

// this is used so you only ever have to do
// inflation and finding by ID once ever per View
private static class ViewHolder {
    public ImageView thumbnailImageView;
    public TextView titleTextView;

}

public void updateData(JSONArray jsonArray) {
    // update the adapter's dataset
    mJsonArray = jsonArray;
    notifyDataSetChanged();
}
}

Just remove below from your JSONAdapter and it will work just fine :) 只需从您的JSONAdapter删除它,它就可以正常工作:)

@Override
public boolean isEnabled (int position) {
   return false;
}

if not atleast return true . 如果不是至少返回true

Have a look here for more info. 在这里查看更多信息。

Though a very old question, but I am still posting an answer to it so that it may help some one. 虽然这是一个非常古老的问题,但我仍然会发布一个答案,以便它可以帮助某个人。 As are using a layout inside the list view, use .. 正如在列表视图中使用布局一样,使用..

android:descendantFocusability="blocksDescendants" 

.. on the first parent layout inside the list. ..在列表中的第一个父布局上。 This works as magic the click will not be consumed by any element inside the list but will directly go to the list item. 这就像魔术一样,点击不会被列表中的任何元素占用,而是直接转到列表项。

Try this and let me know if it works. 试试这个,让我知道它是否有效。 Remove the 除掉

implements AdapterView.OnItemClickListener 

And add: 并添加:

mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(SportsActivity.this,"Clicked",Toast.LENGTH_SHORT).show();
    }
});

In your row.xml add this attribute in TextView and ImageView row.xmlTextViewImageView添加此属性

android:focusableInTouchMode="false" 

This may work. 这可能有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM