I want to add a button in every list item and when the user press it to make a phone call. But when the user press the text, nothing happens..is that possible? This is my code:
public class museum extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.museum);
ListView list = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "Archaeological Museum of Chania");
map.put("address", "Chalidon 21 , Chania");
mylist.add(map);
map = new HashMap<String, String>();
map.put("name", "Byzantine Museum");
map.put("address", "Theotokopoulou 82 , Chania");
mylist.add(map);
// ...
ListAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.row_museum,
new String[] {"name", "address"}, new int[] {R.id.TextView01, R.id.TextView02});
list.setAdapter(mSchedule);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
}
}
});
}
}
Ya you can do. For that
You will have to create a layout file for the list row that contains the textview and the button.
Use that layout inside a customized ArrayAdapter.
See an eg in this site.
You must have a custom list adapter like the one given below.
public class CustomListAdapter extends BaseAdapter {
private ArrayList<SingleElementDetails> allElementDetails;
private Context con;
private LayoutInflater mInflater;
public CustomListAdapter(Context context, ArrayList<SingleElementDetails> results) {
allElementDetails = results;
mInflater = LayoutInflater.from(context);
con=context;
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(R.layout.listview1, null);
Button bt=(Button)convertView.findViewById(R.id.bt);
TextView textview1= (TextView) convertView.findViewById(R.id.dishname_entry);
TextView textview2 = (TextView) convertView.findViewById(R.id.category_entry);
TextView textview3=(TextView)convertView.findViewById(R.id.description_entry);
textview1.setText(allElementDetails.get(position).getDishName());
textview2.setText(allElementDetails.get(position).getCategory());
textview3.setText(allElementDetails.get(position).getDescription());
bt.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Intent intent=new Intent(con,MainActivity.class);
con.startActivity(intent);
}
});
return convertView;
}
}
you can use a Custom adapter like this:
ListView lv_ArchivePartylist;
ArrayList<Parties> select_archived_party;
lv_ArchivePartylist = (ListView)findViewById(R.id.archive_ListView01);
lv_ArchivePartylist.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// TODO Auto-generated method stub
if(view.findViewById(R.id.img_chkbox_archive).getVisibility()==TextView.GONE)
{
view.findViewById(R.id.img_chkbox_archive).setVisibility(TextView.VISIBLE);
Toast.makeText(ctx_archive, "Name="+archived_parties.get(position).getPartyTitle(), Toast.LENGTH_SHORT).show();
select_archived_party.add(archived_parties.get(position));
}
}
});
Then,instead of textview,use buttons and on that button's individual click event,you can write the code to make a call...Hope it helps:-)
Related
I'm new to Android. I want use a SimpleAdapter with a custom layout. Do I have store the original data and then use the id to access it? the view parameter should be something that I can use. But what is the proper way to do it?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_section);
ListView listView = (ListView) findViewById(R.id.MyListView);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
for(int i=0;i<30;i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("ItemTitle", "This is Title.....");
map.put("ItemText", "This is text.....");
mylist.add(map);
}
SimpleAdapter mSchedule = new SimpleAdapter(this,
mylist,
R.layout.list_delegate,
new String[] {"ItemTitle", "ItemText"},
new int[] {R.id.ItemTitle,R.id.ItemText});
listView.setAdapter(mSchedule);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Log.d(TAG, "clicked: " + view);
}
});
}
//simplified activity_section.xml
<LinearLayout
android:id="#+id/MyListItem">
<TextView
android:id="#+id/ItemTitle"/>
<TextView
android:id="#+id/ItemText"/>
</LinearLayout>
Use findViewById to access ItemTitle and ItemText from clicked row of ListView as:
String itemTitle = ((TextView)
view.findViewById(R.id.ItemTitle)).getText().toString();
Do same for accessing ItemText TextView value
After a tremendous amount of time searching in here, and everywhere else I am hopeless to find a solution.
So here is my problem.
I have created a list-view and on top of that I added a search-bar.
When I use the search-bar, to filter the results... when I click on item 7, instead of opening the specific clicked activity i.e. 7, it always starts from the first one.
I am looking forward to your help guys; because I need it!
public class Group extends ListActivity {
// ArrayList thats going to hold the search results
ArrayList<HashMap<String, Object>> searchResults;
// ArrayList that will hold the original Data
ArrayList<HashMap<String, Object>> originalValues;
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grouplist);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
ListView playersListView = (ListView) findViewById(android.R.id.list);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
ListView playersListView = (ListView) findViewById(android.R.id.list);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// these arrays are just the data that
// I'll be using to populate the ArrayList
String names[] = {/*list of names*/ };
String teams[] = {/*list of teams*/};
Integer[] photos = {R.drawable.... /*list of drawables*/};
Integer[] id ={/*Position*/};
originalValues = new ArrayList<HashMap<String, Object>>();
// temporary HashMap for populating the Items in the ListView
HashMap<String, Object> temp;
// total number of rows in the ListView
int noOfPlayers = names.length;
// now populate the ArrayList players
for (int i = 0; i < noOfPlayers; i++) {
temp = new HashMap<String, Object>();
temp.put("name", names[i]);
temp.put("team", teams[i]);
temp.put("photo", photos[i]);
temp.put("id", id[i]);
// add the row to the ArrayList
originalValues.add(temp);
}
// searchResults=OriginalValues initially
searchResults = new ArrayList<HashMap<String, Object>>(originalValues);
final CustomAdapter adapter = new CustomAdapter(this, R.layout.players, searchResults);
// finally,set the adapter to the default ListView
playersListView.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// get the text in the EditText
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
// clear the initial data set
searchResults.clear();
for (int i = 0; i < originalValues.size(); i++) {
String playerName = originalValues.get(i).get("name").toString();
if (textLength <= playerName.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
searchResults.add(originalValues.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
});
// listening to single list item on click
playersListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos=Integer.ParseInt(searchResults.get(position).get("id").toString());
switch (pos) {
case 0:
Intent newActivity = new Intent(TeamsList.this, Barca.class);
startActivity(newActivity);
break;
case 1:
etc...
}
}
}
});
}
Custom adapter Class:
private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>> {
public CustomAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {
// let android do the initializing :)
super(context, textViewResourceId, Strings);
}
// class for caching the views in a row
private class ViewHolder {
ImageView photo;
TextView name, team;
}
ViewHolder viewHolder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.players, null);
viewHolder = new ViewHolder();
// cache the views
viewHolder.photo = (ImageView) convertView.findViewById(R.id.photo);
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.team = (TextView) convertView.findViewById(R.id.team);
//Take one textview in listview design named id
viewHolder.id = (TextView) convertView.findViewById(R.id.id);
// link the cached views to the convert view
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) convertView.getTag();
int photoId = (Integer) searchResults.get(position).get("photo");
// set the data to be displayed
viewHolder.photo.setImageDrawable(getResources().getDrawable(photoId));
viewHolder.name.setText(searchResults.get(position).get("name").toString());
viewHolder.team.setText(searchResults.get(position).get("team").toString());
viewHolder.id.setText(searchResults.get(position).get("id").toString());
// return the view to be displayed
return convertView;
}
}
}
I think you cant find correct position on listview item click. so u can use one textview with visibility="Gone" and insert the position in that textview in every row. now u can easily access position while clicking on item with the value of textview which shows perfect position. Hope it works. Thanx
The problem is that Adapter is populated once but with search results it gets overViewed by the searched items so on clicking it refers to the original items of list instead of the filtered list once , so we have to use the filtered lists' positions instead of the original one, i also faced this problem, try this:
In your listView.setOnItemClickListener
playersListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//Object objFilteredItem = parent.getItemAtPosition(position);
//String a = searchResults.get(position);
switch (Integer.parseInt((String) adapter.getItem(position))) {
case 0:..
Intent newActivity = new Intent(TeamsList.this,Barca.class);
startActivity(newActivity);
break;
case 1:
etc...
break;
}
}
});
As from my previously answered question here, you have to override the getItem(position) method in your CustomAdapter. You are setting the onItemClick somewhat correctly but the list adapter doesn't know what exactly it's getting from getItem(position).
EDIT (details): You need to add something like this in your custom adapter -
#Override
public Object getItem(int position) {
return list.get(position);
}
You should already have the list in your custom adapter. If not, you can add a list reference to your CustomAdapter:
private ArrayList<HashMap<String, Object>> list;
Then setting it using a setter in your Group activity:
customAdapter.setList(searchResults);
I have a listview in android that displays person information from Database.
The listview is given an OnItemClickListener() . Inside the OnItemClickListener() I have also added few onClickListener() for the buttons in the listview item. On running the application , the buttons in the listview are not clickable or the OnClickListener() assigned for the buttons are not getting fired. This issue will no longer appear , once the item in the listview is clicked.All the button click listeners are working after that.
Can somebody give me a solution for this.The code I am using is the follows.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int listrowposition = arg2;
HashMap<String, String> item = (HashMap<String, String>) arg0
.getAdapter().getItem(arg2);
final String id = item.get("ID");
Button vd = (Button) arg1.findViewById(R.id.viewDetails);
// this onclick listener is not working bfore the onitemclick
// listener
vd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),
"view details clicked Id " + id,
Toast.LENGTH_LONG).show();
}
});
Button gd = (Button) arg1.findViewById(R.id.getDirections);
// this onclick listener is not working bfore the onitemclick
// listener
gd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),
"getDirections clicked Id " + id,
Toast.LENGTH_LONG).show();
}
});
Button ra = (Button) arg1.findViewById(R.id.reqAppointment);
// this onclick listener is not working bfore the onitemclick
// listener
ra.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),
"reqAppointment clicked Id " + id,
Toast.LENGTH_LONG).show();
}
});
}
});
The adapter i am using Is a SimpleAdapter .The adapter details are the follows.
String[] from = { "flag", "txt", "cur", "viewDet", "getDirect",
"reqAppnmnt" };
// Ids of views in listview_layout
int[] to = { R.id.flag, R.id.name, R.id.specialization,
R.id.viewDetails, R.id.getDirections, R.id.reqAppointment };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
adapter = new SimpleAdapter(getBaseContext(), aList,
R.layout.listview_layout, from, to);
new CallToServer(adapter, aList).execute("");
// Getting a reference to listview of main.xml layout file
ListView listView = (ListView) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
listView.setOnScrollListener(this);
Row xml must have this line android:descendantFocusability="blocksDescendants"
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// All your widgets here
</LinearLayout>
First of all create a custom adapter. This might help you Custom Adapter for List View
Then add these methods in your adapter
private OnClickListener vdClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "vd clicked, row %d", position);
}
};
private OnClickListener gdClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "gd clicked, row %d", position);
}
};
private OnClickListener ravClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "ra clicked, row %d", position);
}
};
mListView is the listview you are using.
In your adapter getView method do something like this
Button vd = (Button) convertView.findViewById(R.id.viewDetails);
Button gd = (Button) convertView.findViewById(R.id.getDirections);
Button ra = (Button) convertView.findViewById(R.id.reqAppointment);
vd.setOnClickListener(vdClickListener);
gd.setOnClickListener(gdClickListener);
ra.setOnClickListener(raClickListener);
EDIT
A general code to make custom simple adapter is. You need to make changes in getVeiw() method.
public class MyAdapter extends SimpleAdapter{
HashMap<String, String> map = new HashMap<String, String>();
public Adapter(Context context, List<? extends Map<String, String>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
if (row == null) {
LayoutInflater mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.mylistlayout, parent, false);
}
TextView rw1 = (TextView)findViewById(R.id.row1);
rw1.setText("my text");
return row;
}
}
As you can see, i have a listview with textviews and a button pressing of which causes a phone call. The problem is that after selecting a list item ( which always works) pressing the button leads to weird behavior: sometimes it works, sometimes it does not. I have read similar topics but was unable to find a solution. Any help would be appreciated
for (i = 0; i < final_itinList.size(); i++) {
final_itinList.get(i).put("num", String.valueOf(i + 1));
String timi = final_itinList.get(i).get("diff");
final_itinList.get(i).put("diff", timi + "Km");
}
final ListAdapter adapter = new SimpleAdapter(
CheckItineraries.this, final_itinList,
R.layout.list_item2, new String[] { "num",
"startPoliPro", "finalPoliPro", "diff" },
new int[] { R.id.number_n, R.id.startpoli,
R.id.finalpoli, R.id.numKm });
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View container, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, Object> obj = (HashMap<String, Object>) adapter.getItem(position-1);
final String phone_number = (String) obj.get("phone_number");
Button btnphone = (Button) findViewById(R.id.btnphone);
btnphone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View btnphone) {
try {
Intent intent = new Intent(
Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+phone_number));
startActivity(intent);
} catch (Exception e) {
Log.e("Demo application",
"Failed to invoke call", e);
}
There are couple of things which not seems to be right in your code snippet using ListView. I would recommend to look into Google I/O presentation for proper using ListView in android.
The problem in your code snippet that you're trying to bind the button action event on ListView row Item onClick event - which is completely wrong! You've to override the getView method of adapter and inflate the childview for each row item with provided dataset.
For example:
public class CustomAdapter extends SimpleAdapter {
private Context context;
private int layoutResId;
public CustomAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super (context, data, resource, from, to);
// hold the items
this.context = context;
this.layoutResId = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
if (converView == null) {
// inflate the layout
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
// well set up the ViewHolder
viewHolder = new ViewHolderItem();
viewHolder.phoneBtn = (Button)view.findById(R.id.btnphone);
// store the holder with the view.
convertView.setTag(viewHolder);
}
else {
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
viewHolder = (ViewHolderItem) convertView.getTag();
}
// Don't know the purpose of position-1 here.
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position-1);
if (data != null) {
String phone_number = (String)data.get("phone_number");
// set button action
viewHolder.phoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phone_number));
startActivity(intent);
} catch (Exception e) {
Log.e("Demo application", "Failed to invoke call", e);
}
}
}
}
}
/**
* Hold View items
*/
static class ViewHolderItem {
private Button phoneBtn;
}
}
Now you can create the object of CustomAdapter and assign to ListView.
CustomAdapter adapter = new CustomAdapter(
CheckItineraries.this,
final_itinList,
R.layout.list_item2,
new String[] { "num", "startPoliPro", "finalPoliPro", "diff" },
new int[] { R.id.number_n, R.id.startpoli, R.id.finalpoli, R.id.numKm });
// set the adapter
list.setAdapter(adapter);
Note: The ViewHolderItem defined earlier is android design pattern that reduce the look-ups findViewById() and increase the performance for smooth scrolling. You can find more about it here.
You are setting a button listener inside an list item listener.
That means: when you click a list item, the button click listener is set. Only then can you click that specific button to invoke the call.
What you have to do is to create a custom adapter, that sets the button listener once the list item is inflated (created). Here's an example:
for (i = 0; i < final_itinList.size(); i++) {
final_itinList.get(i).put("num", String.valueOf(i + 1));
String timi = final_itinList.get(i).get("diff");
final_itinList.get(i).put("diff", timi + "Km");
}
final ListAdapter adapter = new SimpleAdapter(
CheckItineraries.this, final_itinList,
R.layout.list_item2, new String[] { "num",
"startPoliPro", "finalPoliPro", "diff" },
new int[] { R.id.number_n, R.id.startpoli,
R.id.finalpoli, R.id.numKm }) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
// Fetch the phone number (dunno why you have position-1...)
HashMap<String, Object> obj = (HashMap<String, Object>) getItem(position-1);
final String phone_number = (String) obj.get("phone_number");
Log.d("phone", phone_number);
// Set the button click listener
Button btnphone = (Button) view.findViewById(R.id.btnphone);
btnphone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View btnphone) {
try {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phone_number));
startActivity(intent);
} catch (Exception e) {
Log.e("Demo application", "Failed to invoke call", e);
}
}
});
return view;
}
};
Note: This way of re-setting the button listener is inefficient, but nevertheless it should work (as long as your other code works). If you run into further problems you should ask another question.
So I'm trying to make a basic foreground for another app I'm making.
I'm just trying to get a listView to populate on screen within my fragment. (To create swipe-able tab views)
I keep getting a nullPointerException on this line here:
List.setAdapter(Adapter);
Here's my entire class:
public class List_View extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listviewtest, container, false);
ListView List = (ListView) getActivity().findViewById(R.id.listView1);
List<HashMap<String, String>> Data = new ArrayList<HashMap<String, String>>();
{
HashMap<String, String> temp1 = new HashMap<String, String>();
temp1.put("Item", "Item 1");
Data.add(temp1);
HashMap<String, String> temp2 = new HashMap<String, String>();
temp2.put("Item", "Item 2");
Data.add(temp2);
HashMap<String, String> temp3 = new HashMap<String, String>();
temp3.put("Item", "Item 3");
Data.add(temp3);
}
SimpleAdapter Adapter = new SimpleAdapter(this.getActivity(),
Data, R.layout.custom_row_view, new String[] {
"Item" }, new int[] { R.id.text1});
List.setAdapter(Adapter);
List.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 1:
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(
getActivity());
dlgAlert.setMessage("Set Message Text");
dlgAlert.setTitle("Set Message Title");
dlgAlert.setNeutralButton("View info",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dlgAlert.setCancelable(false);
dlgAlert.create().show();
break;
}
}
});
return rootView;
}
}
So far as I can tell this shouldn't be returning null..
I'm thinking your inflate operation is returning null. Check this line
ListView List = (ListView) getActivity().findViewById(R.id.listView1);
You should be inflating your ListView from your parent view of your fragment, not from the parent activity.
Should be something like this instead
ListView List = (ListView) rootView.findViewById(R.id.listView1); and make sure that