在Listview中未选择正确的项目

时间:2013-12-06 07:17:36

标签: android listview android-listview

我正在使用此Tutorial来创建带有单选按钮的自定义列表视图。在本教程中,当我们单击列表中的项目时,项目的颜色会发生变化。

这种情况发生在我测试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>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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;
    }

}

最后你的Model类

public class GoModelAll {

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

}