setOnItemClickListener在list-view android中不起作用

时间:2014-01-07 08:26:31

标签: android android-listview android-activity onitemclicklistener

我试图通过单击列表视图中加载的列表项来移动到其他活动,但我不知道为什么当我点击任何列表项时没有移动到任何其他活动没有任何事情发生没有崩溃,没有动向其他活动。任何人都可以帮助我。

我搜索了很多并得到了很多解决方案,但任何解决方案都不适用于我的情况。请帮助下面是我的活动代码。

public class Classes_Ext_DB extends Activity implements OnClickListener {

ImageView imageViewNewClass, imageViewDelete;
ListView mListView;

/** Sliding Menu */
boolean alreadyShowing = false;
private int windowWidth;
private Animation animationClasses;
private RelativeLayout classesSlider;
LayoutInflater layoutInflaterClasses;
ArrayAdapter<CharSequence> adapterSpinner;

private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_classDetail = "server detail/get_all_classdetail.php";

// url to delete product
private static final String url_delete_class = "server-detail/delete_class.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_ID = "ID";
private static final String TAG_CLASSNAME = "class_name";

// products JSONArray
JSONArray products = null;

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.classes);

    imageViewNewClass = (ImageView) findViewById(R.id.newclass);
    imageViewDelete = (ImageView) findViewById(R.id.deletemenu);
    mListView = (ListView) findViewById(R.id.displaydata);

    productsList = new ArrayList<HashMap<String, String>>();

    Display display = getWindowManager().getDefaultDisplay();
    windowWidth = display.getWidth();
    display.getHeight();
    layoutInflaterClasses = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View item,
                int position, long id) {
            Intent mIntent = new Intent(Classes_Ext_DB.this,
                    RecordAudio.class);
            startActivity(mIntent);
        }
    });

    new LoadAllClassDetail().execute();

    imageViewNewClass.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Classes_Ext_DB.this,
                    Class_Create_Ext_DB.class);
            startActivityForResult(intent, 100);
        }
    });

    imageViewDelete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                    Classes_Ext_DB.this);

            final Spinner spinnerDelete = new Spinner(Classes_Ext_DB.this);
            alertDialog.setView(spinnerDelete);

            adapterSpinner = ArrayAdapter.createFromResource(
                    Classes_Ext_DB.this, R.array.delete_menu,
                    android.R.layout.simple_spinner_item);
            adapterSpinner
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerDelete.setAdapter(adapterSpinner);

            alertDialog.setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            if (spinnerDelete.getSelectedItemPosition() == 0) {
                                new DeleteProduct().execute();
                            }
                        }
                    });
            alertDialog.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            alertDialog.show();

        }
    });

    findViewById(R.id.skirrmenu).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!alreadyShowing) {
                alreadyShowing = true;
                openSlidingMenu();
            }
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100 then load item by reloading activity again
    if (resultCode == 100) {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}

class LoadAllClassDetail extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Classes_Ext_DB.this);
        pDialog.setMessage("Loading Classes. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_classDetail,
                "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Classes: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String cid = c.getString(TAG_ID);
                    String cn = c.getString(TAG_CLASSNAME);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, cid);
                    map.put(TAG_CLASSNAME, cn);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        Class_Create_Ext_DB.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {

        // dismiss the dialog after getting all products
        pDialog.dismiss();

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {

                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        Classes_Ext_DB.this, productsList,
                        R.layout.custom_class, new String[] {
                                TAG_CLASSNAME, TAG_ID },
                        new int[] { R.id.classname });
                mListView.setAdapter(adapter);
                mListView.setCacheColorHint(Color.TRANSPARENT);
            }
        });
    }
}

/*****************************************************************
 * Background Async Task to Delete Class
 * */
class DeleteProduct extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Classes_Ext_DB.this);
        pDialog.setMessage("Deleting Class... Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Deleting product
     * */
    protected String doInBackground(String... args) {

        // Check for success tag
        int success;
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("ID", TAG_ID));

            // getting product details by making HTTP request
            JSONObject json = jParser.makeHttpRequest(url_delete_class,
                    "POST", params);
            // check your log for json response
            Log.d("Delete Product", json.toString());
            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
    }
}

private void openSlidingMenu() {
    // showFadePopup();
    int width = (int) (windowWidth * 0.8f);
    translateView((float) (width));
    @SuppressWarnings("deprecation")
    int height = LayoutParams.FILL_PARENT;
    // creating a popup
    final View layout = layoutInflaterClasses.inflate(
            R.layout.option_popup_layout,
            (ViewGroup) findViewById(R.id.popup_element));

    ImageView imageViewassignment = (ImageView) layout
            .findViewById(R.id.assignment);
    imageViewassignment.setOnClickListener(this);

    ImageView imageViewfacebook = (ImageView) layout
            .findViewById(R.id.likefb);
    imageViewfacebook.setOnClickListener(this);

    ImageView imageViewTwitter = (ImageView) layout
            .findViewById(R.id.twitter);
    imageViewTwitter.setOnClickListener(this);

    ImageView imageViewBattery = (ImageView) layout
            .findViewById(R.id.battery);
    imageViewBattery.setOnClickListener(this);

    ImageView imageViewAudio = (ImageView) layout.findViewById(R.id.audio);
    imageViewAudio.setOnClickListener(this);

    ImageView imageViewTakeNotes = (ImageView) layout
            .findViewById(R.id.takenote);
    imageViewTakeNotes.setOnClickListener(this);

    ImageView imageViewAllNotes = (ImageView) layout
            .findViewById(R.id.allnotes);
    imageViewAllNotes.setOnClickListener(this);

    ImageView imageViewReportBug = (ImageView) layout
            .findViewById(R.id.reportbug);
    imageViewReportBug.setOnClickListener(this);

    ImageView imageViewFeedback = (ImageView) layout
            .findViewById(R.id.feedback);
    imageViewFeedback.setOnClickListener(this);

    final PopupWindow optionsPopup = new PopupWindow(layout, width, height,
            true);
    optionsPopup.setBackgroundDrawable(new PaintDrawable());
    optionsPopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
    optionsPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
        public void onDismiss() {
            // to clear the previous animation transition in
            cleanUp();
            // move the view out
            translateView(0);
            // to clear the latest animation transition out
            cleanUp();
            // resetting the variable
            alreadyShowing = false;
        }
    });
}

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.assignment:
        Intent assign = new Intent(Classes_Ext_DB.this, Assignment.class);
        startActivity(assign);
        break;

    case R.id.likefb:
        Intent facebook = new Intent(Classes_Ext_DB.this,
                FacebookLogin.class);
        startActivity(facebook);
        break;

    case R.id.facebooklogin:
        Intent twitter = new Intent(Classes_Ext_DB.this, TwitterLogin.class);
        startActivity(twitter);
        break;

    case R.id.battery:
        AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
                Classes_Ext_DB.this);
        myDialogBattery.setTitle("How to use Less Battery");

        TextView textViewBattery = new TextView(Classes_Ext_DB.this);
        ImageView imageViewBattery = new ImageView(Classes_Ext_DB.this);

        imageViewBattery.setImageResource(R.drawable.batteryicon);
        textViewBattery
                .setText("The best way to use less amount of battery possible is to lower the brightness level on your device");
        textViewBattery.setTextColor(Color.GRAY);
        textViewBattery.setTextSize(20);
        LayoutParams textViewLayoutParamsBattery = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        textViewBattery.setLayoutParams(textViewLayoutParamsBattery);

        LinearLayout layoutBattery = new LinearLayout(Classes_Ext_DB.this);
        layoutBattery.setOrientation(LinearLayout.VERTICAL);
        layoutBattery.addView(textViewBattery);
        layoutBattery.addView(imageViewBattery);

        myDialogBattery.setView(layoutBattery);
        myDialogBattery.setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    // do something when the button is clicked
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                });
        myDialogBattery.show();
        break;

    case R.id.audio:
        AlertDialog.Builder myDialogAudio = new AlertDialog.Builder(
                Classes_Ext_DB.this);
        myDialogAudio.setTitle("How to get better audio notes");

        TextView textViewAudio = new TextView(Classes_Ext_DB.this);
        ImageView imageViewAudio = new ImageView(Classes_Ext_DB.this);

        imageViewAudio.setImageResource(R.drawable.micicon);
        textViewAudio
                .setText("Getting the best sounding audio is important, to make sure you are getting the best audio notes possible always ensure that the microphone is facing the speakes.");
        textViewAudio.setTextColor(Color.GRAY);
        textViewAudio.setTextSize(20);
        LayoutParams textViewLayoutParams = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        textViewAudio.setLayoutParams(textViewLayoutParams);

        LinearLayout layoutAudio = new LinearLayout(Classes_Ext_DB.this);
        layoutAudio.setOrientation(LinearLayout.VERTICAL);
        layoutAudio.addView(textViewAudio);
        layoutAudio.addView(imageViewAudio);

        myDialogAudio.setView(layoutAudio);

        myDialogAudio.setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                });
        myDialogAudio.show();
        break;

    case R.id.takenote:
        Intent takenote = new Intent(Classes_Ext_DB.this,
                Classes_Ext_DB.class);
        startActivity(takenote);
        break;

    case R.id.allnotes:
        Intent allNotes = new Intent(Classes_Ext_DB.this, RecordAudio.class);
        startActivity(allNotes);
        break;

    case R.id.reportbug:
        Intent reportBug = new Intent(Classes_Ext_DB.this, ReportBug.class);
        startActivity(reportBug);
        break;

    case R.id.feedback:
        Intent feedback = new Intent(Classes_Ext_DB.this, Feedback.class);
        startActivity(feedback);
        break;
    }
}

private void translateView(float right) {
    animationClasses = new TranslateAnimation(0f, right, 0f, 0f);
    animationClasses.setDuration(100);
    animationClasses.setFillEnabled(true);
    animationClasses.setFillAfter(true);

    classesSlider = (RelativeLayout) findViewById(R.id.classes_slider);
    classesSlider.startAnimation(animationClasses);
    classesSlider.setVisibility(View.VISIBLE);
}

private void cleanUp() {
    if (null != classesSlider) {
        classesSlider.clearAnimation();
        classesSlider = null;
    }
    if (null != animationClasses) {
        animationClasses.cancel();
        animationClasses = null;
    }
}
}

修改

MyXML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/classes_slider"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back_bg"
android:orientation="vertical" >


<ImageView
    android:id="@+id/headerbar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/headerbar_small" />

<ImageView
    android:id="@+id/skirrlogo"
    android:layout_width="100dp"
    android:layout_height="30dp"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="50dp"
    android:layout_marginTop="10dp"
    android:src="@drawable/skirrwhite" />

<ImageView
    android:id="@+id/skirrmenu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="15dp"
    android:src="@drawable/slideropener" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/skirrlogo"
    android:layout_marginLeft="15dp"
    android:layout_toRightOf="@+id/skirrlogo"
    android:text="@string/classses"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textStyle="bold" />

<ImageView
    android:id="@+id/newclass"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/headerbar"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp"
    android:src="@drawable/class_button_new" />

<ImageView
    android:id="@+id/deletemenu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/skirrlogo"
    android:src="@drawable/menubutton_large" />

<ListView
    android:id="@+id/displaydata"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/newclass" >

</ListView>

</RelativeLayout>

custom_class.xml

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

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/classname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dip"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="#000000"
    android:textStyle="bold" />

</LinearLayout>

6 个答案:

答案 0 :(得分:3)

问题是Android不允许您选择包含可关注元素的列表项。我修改了列表项的复选框,使其具有如下属性:

 android:focusable="false"
 android:focusableInTouchMode="false"

现在我的包含复选框的列表项(也适用于按钮)在传统意义上是“可选择的”(它们点亮,您可以单击列表项中的任何位置,“onListItemClick”处理程序将触发等)。 / p>

答案 1 :(得分:2)

添加此

 android:descendantFocusability="blocksDescendants

custom_class.xml

中的根元素

当您单击列表项时,可能复选框会获得焦点。所以只需将上面的内容添加到xml中的根元素中。

http://developer.android.com/reference/android/view/ViewGroup.html#attr_android:descendantFocusability

android:descendantFocusability

在查找要获得焦点的视图时定义ViewGroup及其后代之间的关系。

必须是以下常量值之一。

Constant          Value   Description
beforeDescendants   0      The ViewGroup will get focus before any of its descendants.
afterDescendants    1      The ViewGroup will get focus only if none of its descendants want it.
blocksDescendants   2      The ViewGroup will block its descendants from receiving focus.
This corresponds to the global attribute resource symbol descendantFocusability.

您也可以添加

 android:focusable= "false" 

用于复选框

android:focusable

用于控制视图是否可以获得焦点的布尔值。默认情况下,用户无法将焦点移动到视图;通过将此属性设置为true,允许视图获得焦点。此值不会影响直接调用requestFocus()的行为,无论此视图如何,它都将始终请求焦点。它只会影响焦点导航尝试移动焦点的位置。

必须是布尔值,“true”或“false”。

答案 2 :(得分:2)

在custom_class.xml

的复选框中添加android:focusable=false

答案 3 :(得分:0)

更改

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()

mListView.setOnItemClickListener(new OnItemClickListener()

答案 4 :(得分:0)

mListView.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
            Intent mIntent = new Intent(Classes_Ext_DB.this,
                    RecordAudio.class);
            startActivity(mIntent);
        }
    });

答案 5 :(得分:0)

您是否在复选框上尝试过android:focusable =“false”?