2017-02-18 117 views
1

我想根據項目是否被點擊來更改列表項目的背景顏色。我怎樣才能做到這一點!我也試過如下:設置列表項目的背景顏色(如果已點擊)

articleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { 
      // Find the current article that was clicked on 
      Article currentArticle = mAdapter.getItem(position); 

      if (currentArticle.getUrl() != null) { 
       TextView article_TV = (TextView) findViewById(R.id.post_title); 

       if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
       { 
        article_TV.setBackgroundColor(getApplicationContext().getColor(R.color.colorItemClicked)); 
       } 
     else 
            article_TV.setBackgroundColor(getResources().getColor(R.color.colorItemClicked)); 
       } 

     } 
    }); 

更新: - 愚蠢的錯誤是。由ak sacha建議應該是 TextView article_TV =(TextView)view.findViewById(R.id.post_title);

+1

做這樣的..」的TextView article_TV =(TextView的)view.findViewById(R。 id.post_title);」 –

+0

它解決了!愚蠢的錯誤! –

+0

你做了我說的嗎? –

回答

1

正如ak sacha所建議的,我們可以簡單地通過使用 TextView article_TV =(TextView)view.findViewById(R.id.post_title); 這是因爲我們正在使用的適配器,所以我們需要找到列表視圖row.Hence內的觀點,我們使用view.findviewbyid