2016-12-21 35 views
1

我的代碼列表視圖getChildAt()爲null

public class Products extends AppCompatActivity { 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.addproducts); 
     FillList fillList = new FillList(); 
     fillList.execute(""); 

    } 
    public class FillList extends AsyncTask<String, String, String> { 

     List<Map<String, String>> prolist = new ArrayList<Map<String, String>>(); 
     @Override 
     protected void onPreExecute() { 

     } 

     @Override 
     protected void onPostExecute(String r) { 


      String[] from = { "E","D", "C", "B","A"}; 
      int[] views = { R.id.lblMondeh,R.id.lblBes,R.id.lblBed,R.id.lblSharh,R.id.lblDate}; 
      final SimpleAdapter ADA = new SimpleAdapter(Products.this, 
        prolist, R.layout.lsttemplate, from, 
        views); 
      lstSoratHesab.setAdapter(ADA); 
      lstSoratHesab.setVisibility(View.VISIBLE); 

     if(lstSoratHesab.getChildAt(0-lstSoratHesab.getFirstVisiblePosition())!=null)//all time this line is null 
       lstSoratHesab.getChildAt(0).setBackgroundColor(Color.parseColor("#ff00aa63"));//i want change color first row 

     } 

     @Override 
     protected String doInBackground(String... params) { 

      Map<String, String> datanum = new HashMap<String, String>(); 

      datanum.put("E", "e"); 
      datanum.put("D", "d"); 
      datanum.put("C", "c"); 
      datanum.put("B", "b"); 
      datanum.put("A", "a"); 
      prolist.add(datanum); 

     } 
    } 
} 

我想對第一行設置背景顏色。

爲什麼lstSoratHesab.getChildAt(0-lstSoratHesab.getFirstVisiblePosition())lstSoratHesab.getChildAt(0)所有時間爲空?

但列表視圖中有20個行

enter image description here

回答

2

getChildAt(0)將檢索第一行元素,但是你需要把它在一個線程,讓時間在屏幕上顯示的佈局,可以設置爲:

lstSoratHesab.post(new Runnable() { 
    @Override 
    public void run() { 
     if (lstSoratHesab.getChildAt(0) != null) { 
      lstSoratHesab.getChildAt(0) 
        .setBackgroundColor(Color.parseColor("#ff00aa63")); 
     } 
    } 
}); 
+0

你的代碼在'class FillList'中過去了嗎? – ashkufaraz

+0

@ashkufaraz像''onPostExecute'一樣。 – Fllo

+0

謝謝你這個工作,可以更多地解釋這個 – ashkufaraz

0

我懷疑0-lstSoratHesab.getFirstVisiblePosition()爲負。對於負值,getChildAt始終返回null。

+0

沒有,' lstSoratHesab.getChildAt(0)'仍然全部爲空 – ashkufaraz

+0

如果條件不成立,'lstSoratHesab.getChildAt(0)'將不會在您的代碼中被調用。 – F43nd1r