2017-02-20 58 views
0

我必須以編程方式在我的列表視圖中獲取選定行的背景顏色。 我寫這個着色行:在列表視圖中獲取選定行的背景顏色

View v;  
v.setBackgroundColor(context.getResources().getColor(R.color.childArticle)); 

但我無法弄清楚如何獲得該行的顏色,因爲我必須做這樣的事情:

colorOfSelectedRow = v.getBackgroundColor(); 
if(colorOfSelectedRow == MY_COLOR) { 
    // Do something 
} 

謝謝!

編輯: 我想知道按下行的顏色,但不是所有的行都用相同的顏色着色!

+0

如果設置每個項目用相同的顏色,那麼你不知道它的顏色,不要你呢? –

+3

我想你的答案已經回答了[HERE](http://stackoverflow.com/questions/14779259/get-background-color-of-a-layout) –

+0

不!並非所有的行都是彩色的! –

回答

1

可以標籤內設置背景顏色標識如下圖所示,也得到了在color.xml提到

第1顏色代碼編號到標籤顏色的標識。

view.setTag(R.color.childArticle); 

然後,當你想獲得背景顏色從視圖中獲取標籤並解析其值,並從color.xml文件中獲取顏色代碼。

int ColorId = Integer.parseInt(view.getTag().toString()); 
+0

和我如何獲得顏色?我需要在列表視圖中檢索選定行的顏色。我試過這個:'ColorDrawable viewBackground =(ColorDrawable)listViewOrder.getBackground(); int colorId = viewBackground.getColor();'但它給了我** - 1 ** .. –

+0

您還需要在標記中設置顏色。所以標籤可以保存顏色代碼ID,您可以通過顏色代碼訪問顏色。 –

+0

你的代碼給我總是相同的顏色,但我有一些沒有背景顏色的行和紅色背景顏色的行。當我按下一行時,我想知道所選的行是否爲紅色。與您的代碼我總是有相同的結果 –

0

如果沒有顏色背景設置,此代碼將輸出單擊行的顏色字符串或不顯示任何內容。但是你沒有指定你如何設置背景顏色。

ListView listView = (ListView) findViewById(R.id.listView); 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); 
adapter.add("Blue"); 
adapter.add("None"); 
adapter.add("Red"); 
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    int color; 

    Drawable background = view.getBackground(); 
    if (background instanceof ColorDrawable) { 
     color = ((ColorDrawable) background).getColor(); 
     Log.d("MainActivity", Integer.toHexString(color)); 
    } 
    } 
}); 
listView.setAdapter(adapter); 
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
    listView.getChildAt(0).setBackgroundColor(ContextCompat.getColor(MainActivity.this, android.R.color.holo_blue_dark)); 
    listView.getChildAt(2).setBackgroundColor(ContextCompat.getColor(MainActivity.this, android.R.color.holo_red_dark)); 
    } 
}); 
+0

編輯:它總是返回「ffffffff」。你確定是選定的行嗎? –

+0

你能檢查我更新的答案嗎?它用於點擊行,但可以將其更改爲選定的行。你想什麼時候獲得顏色?在幾個行被選中的某個階段點擊? – Agraphie

+0

我真的是listView監聽器的outsite。嘗試想象點擊一個按鈕,它會給你所選列在列表視圖中的顏色。我不知道如何從setOnItemClickListener的外部獲取當前選定的列表視圖的行顏色! –

0
final int MY_COLOR = R.color.childArticle; 
View v;  
v.setBackgroundColor(context.getResources() 
.getColor(R.color.childArticle)); 
view.setTag(R.color.childArticle); 
Integer colorOfSelectedRow = (Integer) v.getTag(); 
if(colorOfSelectedRow == MY_COLOR) { 
// Do something 
} 

使用這個..

相關問題