I'm trying to call onItemClick manually when my fragment first starts up but it does not behave the way expected.It was called in the onCreateView() method as follows:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
handler=new DBHandler(getActivity().getApplicationContext(),null,null,1);
JustaMap=new HashMap<String,List<MediaMetadata>>();
app = new Common();
rootView = inflater.inflate(R.layout.fragment_create_playlist, container, false);
musicProvider = new MusicProvider();
SongTitles = new ArrayList<String>();
PlayList = new ArrayList<MediaMetadata>();
musicProvider.buildSongFromDevice();
SongList = (List<MediaMetadata>) musicProvider.getAllMusics();
Iterator<MediaMetadata> iterator = SongList.iterator();
while (iterator.hasNext())
SongTitles.add(iterator.next().getDescription().getTitle().toString());
listView = (ListView) rootView.findViewById(R.id.listView);
editText = (EditText) rootView.findViewById(R.id.PlaylistName);
button = (Button) rootView.findViewById(R.id.submit);
adapter = new CustomAdapter(getActivity().getApplicationContext(), SongTitles);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
MediaMetadata SongSelected = SongList.get(position);
view.setSelected(true);
if (view.getBackground() == null) {
view.setBackgroundResource(R.color.light_grey);
if (!Arrays.asList(PlayList).contains(SongSelected))
PlayList.add(SongSelected);
} else {
view.setBackgroundResource(0);
PlayList.remove(SongSelected);
}
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// createPlaylist();
}
});
listView.performItemClick(
listView.getAdapter().getView(2,null,null),2,listView.getAdapter().getItemId(2));
return rootView;
}
Basically,when the item is clicked,it's background is supposed to changed to grey but it remains white when the fragment starts up. I've used a debugger to step through and the onItemClick() is still called but the background does not change. However, if I perform the actual click on the list item,it actually works and the color changes as expected. It seems like the view's background got set back to null after calling performItemClick() but not when actual clicks occur. Why is this happening?