I am implementing a ListView by changing the selected item's background in OnItemClick. However, I am not able to "initialize" an item in the app's OnCreate. (I tried using <ListView>.getChildAt(0).setBackgroundColor, but inside of OnCreate, getChildAt(0) returns null.)
Why would you initialize the item? Usually the framework will lay it out (aka "inflate" it)
Basically, can you clarify what you're trying to accomplish? Also how do you add you items to the listview? Are you using a ListActivity? ListFragment? ListView + adapter? etc...
and here is a portion of the app's main .java file:
Code:
String[] Locations;
ListView LocationList;
ArrayList<HashMap<String, String>> LocationAndTypeList = new ArrayList<HashMap<String, String>>(32);
int SelectedLocation;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Populate select_location
// R.array.location points to a StringArray of 25 location names
Location = getResources().getStringArray(R.array.location);
String[] FromList = new String[] {"text1", "text2"};
int[] ToList = new int[] {R.id.text1, R.id.text2};
for (int i = 0; i < Locations.length; i++)
{
HashMap<String, String> M = new HashMap<String, String>();
M.put("text1", Locations[i]);
M.put("text2", "Row " + Integer.toString(i + 1));
LocationAndTypeList.add(M);
}
// Populate the list view
LocationList = (ListView)findViewById(R.id.location_list);
SimpleAdapter LocationListAdapter = new SimpleAdapter(this, LocationAndTypeList, R.layout.twolinelistitemrow, FromList, ToList);
LocationList.setAdapter((ListAdapter)LocationListAdapter);
LocationList.setOnItemClickListener(new LocationListClickListener());
// Set the initially selected value to -1
SelectedLocation = -1;
}
// When an item is clicked, change its background color
public class LocationListClickListener implements OnItemClickListener
{
public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
{
// "Unselect" the previously selected location
if (SelectedLocation >= 0)
{
View previousLocation = parent.getChildAt(SelectedLocation);
previousLocation.setBackgroundColor(Color.TRANSPARENT);
}
SelectedLocation = pos;
view.setBackgroundColor(Color.rgb(0, 80, 0));
}
}
What I want to do is, I want to have the first item in the ListView have its background changed to the "selected" color (RGB(0, 80, 0)) when it first appears.
Thanks for the advice, but even in onResume() (as well as onStart()), getChildAt(0) returns null. In fact, in onResume(), getChildCount() returns zero.
It does work in the click condition, so it most likely is a case of trying to access something that just hasn't been created yet.