Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

android - Correct item is not selected in Listview

I am using this Tutorial for Creating a custom listview with radio button. In this tutorial when we click the item in the list then color of item change.

This is happening when i am testing this code above 4.0 but below 4.0 it is not workin properly I am not understand why????

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

   }
});   

    }
}

My xml View

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Define your variables like this

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

Define your AsyncTask like this

new GoAsyncTask().execute();

Your AsyncTask class Code like this

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

}

Your Adapter class

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

}

At last your Model class

public class GoModelAll {

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...