Skip to content

Instantly share code, notes, and snippets.

@rajiv-singaseni
Created June 28, 2011 18:40
Show Gist options
  • Save rajiv-singaseni/1051848 to your computer and use it in GitHub Desktop.
Save rajiv-singaseni/1051848 to your computer and use it in GitHub Desktop.
A sample program to show how to embed buttons in a listview and run corresponding functions on click of those buttons
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<TextView android:id="@android:id/text1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:text="Some cell"
android:paddingLeft="6dip" />
<Button android:id="@android:id/button1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="Upload"
android:layout_weight="0"
android:paddingRight="6dip" />
</LinearLayout>
package com.webile.listview;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new MyArrayAdapter());
}
@Override
public void onClick(View v) {
Object taggedObject = v.getTag();
int position = ((Integer) taggedObject).intValue();
Toast.makeText(this, String.format("Uploading form at position %d", position), Toast.LENGTH_SHORT).show();
//TODO: Call the custom function in here.
//uploadForm(position);
}
/*
private void uploadForm(int position) {
}
*/
private class MyArrayAdapter extends ArrayAdapter<String> {
public MyArrayAdapter() {
super(MainActivity.this, R.layout.list_button, android.R.id.text1);
}
@Override
public int getCount() {
return 5;
}
@Override
public String getItem(int position) {
return String.format("Cell %d", position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
View buttonView = view.findViewById(android.R.id.button1);
buttonView.setOnClickListener(MainActivity.this);
buttonView.setTag(new Integer(position));
return view;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment