简体   繁体   中英

Custom ListView Adapter nullPointer problem

I am trying to set the first and last elements of a list view to have their backgrounds different to everything in the middle. I have created my custom adapter .xml file and works perfectly when I set everything up statically in their to have each row the same style. As of now i'm just trying to change the first element. I think i'm getting the nullPointerException because i'm not properly referencing the LinearLayout I want the background to be changed. Here is my code:

for (int i = 0; i < categories.size(); i++){
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("name", categories.get(i));
            LinearLayout linear = (LinearLayout)findViewById(R.id.linearLayout1);
            if(i == 0){
                linear.setBackgroundResource(R.drawable.background);
                Log.v("First Element", "First");
            }
            else{
                linear.setBackgroundResource(R.drawable.background);
                Log.v("Not First Element", "Not First");
            }
            mylist.add(map);
        }

I think my problem is due to the fact the R.id.linearLayout1 reference is not in the main xml file for this activity, so how do I get the correct reference. If this is not the case then how do I go about having different backgrounds for the top and last elements of a listView?

You should use "inflate" to get your layout.

example (if i'm not mistaken, can't try it out here)

LinearLayout linear = activity.getViewInflate().inflate(linearLayout1,null, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM