Thursday, June 6, 2013

[android help] Dynamically adding custom row to listview


By referring this, I created following:


main.xml



android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

android:id="@+id/addBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="addItems"
android:text="Add New Item" />

android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false" />





MainActivity.java



public class MainActivity extends Activity {
ListView list;
ArrayList listItems = new ArrayList();
ArrayAdapter adapter;
int clickCounter = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems);
list.setAdapter(adapter);

list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
String item = list.getItemAtPosition(position).toString();
Log.i("MainActivity", "Selected = " + item);
}
});
}

public void addItems(View v) {
listItems.add("Clicked : " + clickCounter++);
adapter.notifyDataSetChanged();
}
}



And it's working perfectly. But as per requirements, my each listview row won't just be a single string. Instead, it'll be collection of views consisting of imageview and textviews stored in row.xml.


Now my queries are:



  • What will replace adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, listItems); ? Will it be adapter = new ArrayAdapter(this,R.layout.row, listItems); ??




  • How do I refer to imageview and textviews of each row? How do I set and get data from them? How do I recognize their click events?




  • Is use of Adapter must? or can I get away with it?



Any help appreciated.



.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...