I am learning Android right now and working on the list view to display multiples items for the list. It might be stupid question but I have to ask to find down the reason behind the scenes ( if there are any )
Below are 2 ways to populate the data to the list view
way 1
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView moblieListView = getListView();
MobileListAdapter mobileListAdapter = new MobileListAdapter(getApplicationContext(), mobileList);
moblieListView.setAdapter(mobileListAdapter);
moblieListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedValue = (String)parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), selectedValue, Toast.LENGTH_SHORT).show();
}
});
}
way 2
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MobileListAdapter mobileListAdapter = new MobileListAdapter(getApplicationContext(), mobileList);
setListAdapter(mobileListAdapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String str = l.getItemAtPosition(position).toString();
Toast.makeText(MobileActivity.this, str, Toast.LENGTH_SHORT).show();
}
What I am seeing right now is way1
is having an object of ListView
, but way2
. Another point is onItemClick
is located in onCreate
in way1
, however, onItemClick is separated from onCreate
in way2
.
Question Are there any particular reasons when we should use way1 over way2 or vice versa. please help if you have any ideas about these.