列表视图getChildAt()为null

时间:2016-12-21 17:04:27

标签: android listview

我的代码

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 个答案:

答案 0 :(得分:2)

getChildAt(0)将检索第一行元素,但您需要在一个线程中获取它以让布局的时间显示在屏幕上,可以设置为:

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

答案 1 :(得分:0)

我怀疑0-lstSoratHesab.getFirstVisiblePosition()是否定的。对于负值,getChildAt始终返回null。