2013-12-06 2 views
-2

Я использую этот Tutorial для создания пользовательского списка с помощью переключателя. В этом учебном пособии, когда мы нажимаем элемент в списке, тогда цвет элемента изменяется.Правильный элемент не выбран в Listview

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

Класс Blog.java

public class Blog extends Activity { 


ListView listView; 

ArrayList< String>arrayList; // list of the strings that should appear in ListView 
ArrayAdapter arrayAdapter; // a middle man to bind ListView and array list 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.custom); 

     listView = (ListView) findViewById(R.id.lstDemo); 


     // LIST OF STRINGS/DATA THAT SHOULD APPEAR IN LISTVIEW HERE WE HAVE HARD CODED  IT WE CAN TAKE THIS INPUT FROM USER AS WELL 

     arrayList = new ArrayList(); 
     arrayList.add("India"); 
     arrayList.add("USA"); 
     arrayList.add("England"); 
     arrayList.add("Singapur"); 
     arrayList.add("China"); 
     arrayList.add("Canada"); 
     arrayList.add("Srilanka"); 
     arrayList.add("SouthAfrica"); 




     arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_single_choice,arrayList); 
     listView.setAdapter(arrayAdapter); 


    // LETS HIGHLIGHT SELECTED ITEMS 

    listView.setOnItemClickListener(new OnItemClickListener() { 

    @Override 
    public void onItemClick(AdapterView arg0, View view, int position, 
long itemId) { 


/* 
* when we click on item on list view we can get it catch item here. 
* so view is the item clicked in list view and position is the position 
* of that item in list view which was clicked. 
* 
* Now that we know which item is click we can easily change the color 
* of text but when we click on next item we we have to deselect the old 
* selected item means recolor it back to default , and then hight the 
* new selected item by coloring it . 
* 
* So here's the code of doing it. 
* 
* 
* */ 


CheckedTextView textView = (CheckedTextView) view; 
for (int i = 0; i < listView.getCount(); i++) { 
textView= (CheckedTextView) listView.getChildAt(i); 
if (textView != null) { 
    textView.setTextColor(Color.WHITE); 
} 

} 
listView.invalidate(); 
textView = (CheckedTextView) view; 
if (textView != null) { 
textView.setTextColor(Color.BLUE); 
} 

    } 
}); 

    } 
} 

Мой XML Посмотреть

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<ListView 
    android:id="@+id/lstDemo" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:choiceMode="singleChoice"> 

</ListView> 

+0

Могу ли я KNW почему это dowgrade мой вопрос – Singhak

+0

Просьба представить более подробную информацию и код для поддержки .... –

+0

As вы не указали свой вопрос. Этот вопрос ничего не значит. Поместите то, что сделал U и что вам нужно – AndroidHacker

ответ

0

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

Установить это в качестве фона для вашего списка пункт:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_pressed="true" android:color="@color/white" /> 
    <item android:color="@color/black" /> 
</selector> 
+0

Вышеприведенный полный код. проверьте его – Singhak

+0

check mu отредактировал ans –

+0

моя проблема в том, что код работает отлично в 4.0 и выше, но не ниже 4.0 – Singhak

0

Определите переменные, как этот

private ProgressDialog pDialog; 
    private ListView lv; 
    private ArrayList<GoModelAll> m_ArrayList = null; 
    GoArrayAdapter gaa; 

Определите ваш AsyncTask как этот

new GoAsyncTask().execute(); 

Ваш AsyncTask код класса, как это

class GoAsyncTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected void onPreExecute() { 
     // TODO Auto-generated method stub 
     super.onPreExecute(); 

     /*pDialog = new ProgressDialog(getActivity()); 
     pDialog.setMessage("Please wait ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show();*/ 
     pd.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     sal = new StaticApiList(); 
     myUrl = StaticApiList.go_api; 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(myUrl); 

     try { 
      HttpResponse httpResponse = httpClient.execute(httpGet); 
      System.out.println("httpResponse"); 

      InputStream inputStream = httpResponse.getEntity().getContent(); 
      InputStreamReader inputStreamReader = new InputStreamReader(
        inputStream); 
      BufferedReader bufferedReader = new BufferedReader(
        inputStreamReader); 
      StringBuilder stringBuilder = new StringBuilder(); 
      String bufferedStrChunk = null; 
      while ((bufferedStrChunk = bufferedReader.readLine()) != null) { 
       stringBuilder.append(bufferedStrChunk); 
      } 
      jsonString = stringBuilder.toString(); 
      Log.i("talk_all_json", jsonString); 
      return stringBuilder.toString(); 

     } catch (ClientProtocolException cpe) { 
      System.out.println("Exception generates caz of httpResponse :" 
        + cpe); 
      cpe.printStackTrace(); 
     } catch (IOException ioe) { 
      System.out 
        .println("Second exception generates caz of httpResponse :" 
          + ioe); 
      ioe.printStackTrace(); 
     } 

     return null; 
    } 

    @SuppressWarnings("static-access") 
    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
     vivek = true; 
     try{ 
      m_ArrayList = new ArrayList<GoModelAll>(); 
      if (jsonString.length() > 0) { 
        JSONArray jArray = new JSONArray(jsonString); 
         dh.open(); 
         for(int i=0; i < jArray.length(); i++) { 

          JSONObject jObject = jArray.getJSONObject(i); 

          description = jObject.getString("description"); 
          excert = jObject.getString("excert"); 
          thumsrc = jObject.getString("thumsrc"); 
          title = jObject.getString("title"); 
          postid = jObject.getInt("postid"); 
          Log.d("talklog", "Title -> " + title + " , thumsrc -> " + thumsrc 
            + " , excert -> " + excert + " , description -> " + description); 
          Log.d("talklog", "============================= end of " + i + " ==============================="); 

          gma = new GoModelAll(); 
          gma.description = description; 
          gma.excert = excert; 
          gma.thumsrc = thumsrc; 
          gma.title = title; 
          gma.postid = postid; 
          Cursor cursor = dh.getSeenStatus(gma.postid); 
          if(cursor.getCount()>0) 
          { 
           cursor.moveToFirst(); 
           if(cursor.getInt(0) == 0) 
           { 
            gma.isSeen = false; 
           } 
           else 
           { 
            gma.isSeen = true; 
           } 
          } 
          else 
          { 
          ContentValues cv = new ContentValues(); 
          cv.put(DbHandler.KEY_ID, postid); 
          cv.put(DbHandler.KEY_VALUE, 0); 
          dh.addData(DbHandler.TABLE_SEEN, cv); 
          } 
          m_ArrayList.add(gma); 
         } 
         dh.close(); 
      } 

      gaa = new GoArrayAdapter(getActivity(), m_ArrayList); 
      lv = (ListView) getActivity().findViewById(R.id.go_list); 
      lv.setVisibility(View.VISIBLE); 
      lv.setAdapter(gaa); 

      lv.setOnItemClickListener(new OnItemClickListener() { 

       @Override 
       public void onItemClick(AdapterView<?> arg0, View arg1, 
         int arg2, long arg3) { 
        // TODO Auto-generated method stub 
        dh.open(); 
        dh.updateSeenStatus(m_ArrayList.get(arg2).postid, 1); 
        m_ArrayList.get(arg2).isSeen = true; 
        dh.close(); 
        GoDetail fragment = new GoDetail(); 
        Bundle bundle = new Bundle(); 

        bundle.putString("title", m_ArrayList.get(arg2).title); 
        bundle.putString("excert", m_ArrayList.get(arg2).excert); 
        bundle.putString("description", m_ArrayList.get(arg2).description); 
        bundle.putString("thumsrc", m_ArrayList.get(arg2).thumsrc); 
        bundle.putString("header_title", "Go"); 
        //bundle.putInt("postid", m_ArrayList.get(arg2).postid); 

        fragment.setArguments(bundle); 
        ((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true); 
       } 
      }); 

     }catch(Exception e){ 
      e.printStackTrace(); 
     } 

     //pDialog.dismiss(); 
     pd.dismiss(); 
    } 

} 

Ваш адаптер класса

public class GoArrayAdapter extends ArrayAdapter<GoModelAll> { 
    private final Context context; 
    ImageLoader imgLoader; 
    private final ArrayList<GoModelAll> values; 
    DataHelper dh; 
    public GoArrayAdapter(Context context, 
      ArrayList<GoModelAll> values) { 
     super(context, R.layout.go_row, values); 
     this.context = context; 
     this.values = values; 
     imgLoader = new ImageLoader(context); 
     dh = new DataHelper(context); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     LayoutInflater inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View rowView = inflater.inflate(R.layout.go_row, parent, false); 

     /** Get view over here.. */ 
     GoModelAll asm = values.get(position); 
     TextView title = (TextView) rowView.findViewById(R.id.go_tv); 
     ImageView business_logo = (ImageView) rowView.findViewById(R.id.go_image); 
     ImageView go_red = (ImageView)rowView.findViewById(R.id.go_red); 
     if(asm.isSeen) 
     { 
      go_red.setVisibility(View.INVISIBLE); 
     } 
     /**Set view over here..*/ 

     title.setText(asm.title); 

     // Loader image - will be shown before loading image 
     int loader = R.drawable.image_not_available; 
     String image_url = asm.thumsrc; 
     imgLoader.DisplayImage(image_url, loader, business_logo); 

     return rowView; 
    } 

} 

В конце концов ваш класс модели

public class GoModelAll { 

    public String description = ""; 
    public String excert = ""; 
    public String thumsrc = ""; 
    public String title = ""; 
    public int postid = 0; 
    public boolean isSeen = false; 

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