2011-09-16 84 views
0

如何改變列表視圖的背景顏色,當點擊一次,當再次點擊時,我需要改變背景顏色沒有使用selector.I已經在改變背景,當我選擇每個item.but當我再次點擊該項目我需要改變背景顏色爲red.how我可以給condition.i將我的代碼發佈在這裏。請給suggestions.please幫助...如何改變列表視圖的背景顏色,當點擊一次,當再次點擊時,我需要改變背景顏色,而不使用選擇器

公共類ProvierActivity延伸活動{

private String text[] = { "BroadStripe-Cable (Seattle)", 
     "BroadStripe-Digital (Seattle)", "BroadStripe-Cable (Seattle)", 
     "Comcast king county south)", "BroadStripe-Cable (Seattle)", 
     "Comcast king county south", "BroadStripe-Digital (Seattle)", 
     "BroadStripe-Digital (Seattle)", "BroadStripe-Cable (Seattle)", 
     "Comcast king county south" }; 

ImageView icon; 
public static int selectedRow; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    final ListView list = (ListView) findViewById(R.id.listview_id); 

    list.setAdapter(new ArrayAdapter<String>(this, R.layout.list, 
      R.id.title, text)); 
    list.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> adapter, View view, 
       int position, long arg3) { 

      for (int i = 0; i < adapter.getChildCount(); i++) { 
       if (i == position) { 

        adapter.getChildAt(i).setBackgroundColor(Color.BLUE); 

       } else { 
        adapter.getChildAt(i).setBackgroundColor(Color.BLACK); 

       } 

      } 

     } 

    }); 
} 

}

回答

0

使用此編輯的代碼。

public static int selectedRow; 

/** Called when the activity is first created. */ 

private int prePos=-1; 


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

    final ListView list = (ListView) findViewById(R.id.listview_id); 

    list.setAdapter(new ArrayAdapter<String>(this, R.layout.list, 
      R.id.title, text)); 
    list.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> adapter, View view, 
       int position, long arg3) { 

      for (int i = 0; i < adapter.getChildCount(); i++) { 
       if (i == position) { 

        if(position!=prePos){ 
         adapter.getChildAt(i).setBackgroundColor(Color.BLUE); 

         prePos=position; 

        }else{ 
         adapter.getChildAt(i).setBackgroundColor(Color.BLACK); 
          prePos=-1; 
         } 

        }else{ 

         adapter.getChildAt(i).setBackgroundColor(Color.BLACK); 

        } 

       } 


     } 

    }); 
} 

} 

這會幫助你。

+0

感謝您的幫助。我的工作。但我想如果一個被選中,當我們選擇另一個項目時,前一個應該是black.that是我選擇的項目,只應該改變color.can你在這方面的幫助也。 – preeti

+0

你能再清楚一點嗎?我認爲你的代碼符合你的要求。 –

+0

是的,我已經發布我的代碼了。那是工作正常。那就是當我選擇一個項目的顏色改變,當我選擇另一個項目的顏色只改變選定的項目和所有其他項目有黑色背景。但介紹標誌我的需求不起作用。 – preeti