[英]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.
我已经创建了自定义适配器.xml文件,并且当我将它们中的所有内容静态设置为使每一行具有相同样式时,它们可以完美地工作。 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.
我认为我正在获取nullPointerException,因为我没有正确地引用LinearLayout我希望更改背景。 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. 我认为我的问题是由于
R.id.linearLayout1
引用不在此活动的主xml文件中,所以我如何获得正确的引用。 If this is not the case then how do I go about having different backgrounds for the top and last elements of a listView? 如果不是这种情况,那么我该如何为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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.