2011-08-16 3 views
2

У меня есть ListView, который создается вместе с помощью специального адаптера, чтобы я мог показывать все остальные списки в другом цвете. Как написать свой код, чтобы я мог видеть контрольный список без расширения ListActivity (моя активность только расширяет активность) Вот мой код.ListView setChoiceMode не отображается

public class TrackingMe extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 

    setContentView(R.layout.trackingme_layout); 

    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, 
      R.layout.custom_title_3); 

    SharedPreferences prefs = getSharedPreferences("Settings", 0); 
    final String id = prefs.getString("ID", ""); 

    final TextView myTitleText = (TextView) findViewById(R.id.tvTitle3); 
    if (myTitleText != null) 
     myTitleText.setText(getResources().getString(R.string.Trackingme)); 

    ImageButton addFriends = (ImageButton) findViewById(R.id.btnAddFriends); 
    addFriends.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      Intent addFriends = new Intent("com.cellphone.INVITEFOLLOWER"); 
      startActivity(addFriends); 
     } 
    }); 

    final ListView lv2 = (ListView) findViewById(R.id.trackingmelistview); 
    lv2.setChoiceMode(2); 
    lv2.setTextFilterEnabled(true); 
    refreshList(id,lv2); 

    ImageButton refresh = (ImageButton) findViewById(R.id.btnRefresh2); 
    refresh.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 

      refreshList(id, lv2); 

     } 
    }); 
} 

static final ArrayList<HashMap<String, String>> list2 = new ArrayList<HashMap<String, String>>(); 

private void refreshList(String id, ListView lv) { 
    // removes the list and rebuilds it will choose different response 
    // string to get the refreshed times. 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httpost = new HttpPost(
      "http://iphone-radar.com/people_i_follow"); 

    JSONObject holder = new JSONObject(); 
    try { 
     holder.put("userid", id); 
     // pacific time zone for now 

     StringEntity se = new StringEntity(holder.toString()); 
     httpost.setEntity(se); 
     httpost.setHeader("Accept", "application/json"); 
     httpost.setHeader("Content-type", "application/json"); 

     ResponseHandler responseHandler = new BasicResponseHandler(); 
     final String response = httpclient 
       .execute(httpost, responseHandler); 
     list2.removeAll(list2); 


     SpecialAdapter adapter = new SpecialAdapter(this, list2, 
       R.layout.trackingme_row_layout, new String[] { "name" }, new int[] { R.id.tvTrackingMeNames}); 


     org.json.JSONObject obj = new org.json.JSONObject(response); 
     JSONArray tracking_users = obj.getJSONArray("d"); 

     for (int i = 0; i < tracking_users.length(); i++) { 
      // for loop to get all data 
      HashMap<String, String> temp = new HashMap<String, String>(); 
      JSONObject user = tracking_users.getJSONObject(i); 
      temp.put("name", user.getString("full_name")); 
      list2.add(temp); 
      // upload location time 

     } 

     lv.setAdapter(adapter); 
    } catch (JSONException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

} 
    //here is the special adapter so that everyother line is a different color 
    public class SpecialAdapter extends SimpleAdapter { 
private int[] colors = new int[] { Color.GRAY, Color.WHITE }; 

public SpecialAdapter(Context context, 
     ArrayList<HashMap<String, String>> list, int resource, 
     String[] from, int[] to) { 
    super(context, list, resource, from, to); 

} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View view = super.getView(position, convertView, parent); 
    int colorPos = position % colors.length; 
    view.setBackgroundColor(colors[colorPos]); 
    return view; 
} 
    } 

До сих пор оно отображалось как строка текста, основанная на том, что я получаю от своего источника. Однако, когда я нажимаю на отдельные строки, они не выделяются, и хотя я написал lv.setChoiceMode (2), рядом с списком не было флажка. Благодаря

EDIT вот мой trackingme_row_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <TextView 
     android:id="@+id/tvTrackingMeNames" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_marginLeft="31dp"    
     android:text="TextView" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:textColor="#000000"/> 

</RelativeLayout> 

и trackingme_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <ListView 
     android:id="@+id/trackingmelistview" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:paddingTop="10dp"/> 

    <ImageButton 
     android:id="@+id/btnRefresh2" 
     android:text="Refresh" 
     android:src="@android:drawable/stat_notify_sync" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentLeft="true"/> 

</RelativeLayout> 
+1

Лучше использовать предопределенный constants.'lst.setChoiceMode (ListView.CHOICE_MODE_MULTIPLE) ' –

+0

Взглянув на layout.trackingme_row_layout поможет понять. PLease опубликуйте, что xml-макет в ур-вопросе. – Ronnie

+0

Я разместил xml макеты спасибо за вашу помощь – Sean

ответ

3

Вызов setChoiceMode не достаточно, чтобы отобразить флажки рядом список ваших строк. Если вы используете базовый макет для строк, попробуйте android.R.layout.simple_list_item_multiple_choice. Кроме того, вам нужно будет добавить флажок в макет строки & самостоятельно управлять своим состоянием вкл/выкл в методе адаптера getView.

НТН,

Акшай

P.S: вызов setChoiceMode(ListView.CHOICE_MODE_MULTIPLE) вместо setChoiceMode(2).

+1

Привет, я заменил setChoiceMode (2) с помощью setChoiceMode (ListView.CHOICE_MODE_MULTIPLE), но ничего не изменилось. – Sean

+1

CHOICE_MODE_MULTIPLE был всего лишь предложением, он ничего не изменит. Как я уже сказал, setChoiceMode недостаточно для отображения флажков. Вы также должны иметь правильную компоновку для отображения флажков. На простом примере просмотрите http://www.androidpeople.com/android-listview-multiple-choice-example. – Akshay

+0

setChoiceMode (ListView.CHOICE_MODE_MULTIPLE); не работает в моем case.it aint, показывая флажки в listview. –

0

Короткий ответ заключается в том, что listView не работает с макетами.

Простым решением проблемы является удаление макета внешнего устройства и использование флажка или CheckedTextView.

Вот более длинный ответ (ответ Мартина - лучший). What is the difference between the states selected, checked and activated in Android?

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