0

Я пытаюсь перейти к другому действию, нажав на элемент списка, который загружен в виде списка, но я не понимаю, почему он не перемещается в какое-либо другое действие, когда я нажимаю в любом элементе списка ничего не происходит без сбоев, а не для перехода к другой активности. Кто-нибудь может мне помочь.setOnItemClickListener не работает в android-представлении списка

Я искал много и получил так много решений, но любое решение не работает в моем случае. Пожалуйста, помогите ниже - мой код активности.

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> 
+0

У вас возникли какие-либо ошибки? –

+0

Нет, я не получаю никаких ошибок ... – InnocentKiller

+0

Пожалуйста, удалите его :: реализует OnClickListener, если вам это не нужно ... –

ответ

2

Вопрос заключается в том, что Android не позволяет выбрать элементы списка, которые имеют элементы на них, которые фокусирования. Я изменил флажок на элемент списка, чтобы иметь атрибут как так:

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

Теперь мои пункты списка, которые содержат флажки (работает для кнопок тоже) являются «выбор» в традиционном смысле (они загораются, вы можете щелкните в любом месте элемента списка, и обработчик «onListItemClick» запустится и т. д.).

1

Изменить

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() 

в

mListView.setOnItemClickListener(new OnItemClickListener() 
+0

Я тоже пробовал это, но потом тоже он не перешел к следующей активности ... – InnocentKiller

+0

Вы получаете какую-либо ошибку? –

+1

'OnItemClickListener' и' AdapterView.OnItemClickListener '- то же самое. –

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); 
     } 
    }); 
2

Добавить

android:descendantFocusability="blocksDescendants 

к корневому элементу в custom_class.xml

Вероятно флажком принимает фокус при нажатии на элемент списка. Поэтому просто добавьте это в корневой элемент в xml.

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

android:descendantFocusability

Определяет связь между ViewGroup и его потомков, когда ищет View, чтобы получить фокус.

Должно быть одно из следующих постоянных значений.

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

Boolean, который контролирует, может ли вид получить фокус. По умолчанию пользователь не может перемещать фокус на просмотр; установив этот атрибут в true, просмотр может быть сфокусирован.Это значение не влияет на поведение прямого вызова requestFocus(), которое всегда будет запрашивать фокус независимо от этого представления. Это влияет только на то, где фокусировка навигации будет пытаться переместить фокус.

Должно быть логическое значение «true» или «false».

+0

Я должен добавить эту строку в чек-бокс пользовательского класса правильно ??? – InnocentKiller

+1

@InnocentKiller для корневого элемента в вашем xml – Raghunandan

2

Добавить android:focusable=false в флажке custom_class.xml

0

вы пробовали андроид: фокусируемый = «ложь» в окошке?

Смежные вопросы