This question already has answers here:
setOnItemClickListener on custom ListView
(6 answers)
Closed 6 years ago.
I have an ArrayList that has some String variables and I have a custom ArrayAdapter that I populate from the ArrayList. Now when that list in displayed and an item in the list is clicked, I want the program to do something but I don't know how to do it. I looked at a few examples but I didn't understand where exactly to put the code. So here is my code, can you tell me what to do and where to do it?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateList(listOfItems);
}
public void updateList(ArrayList<String> possibleWords){
listAdapter = new CustomListAdapter(this, R.layout.custom_list,possibleWords);
android.R.layout.simple_list_item_1, possibleWords);
final ListView listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(listAdapter);
}
CustomListAdapter.java Class
public class CustomListAdapter extends ArrayAdapter {
private Context mContext;
private int id;
private List<String> items ;
public CustomListAdapter(Context context, int textViewResourceId , List<String> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
return mView;
}
}
Here is a sample image on what the output looks like
So when "act" or "cat" are clicked, I want to do something but I don't know how to handle the click and where to put the code on what I want to do.
Put the below code on your main activity
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
//do your work here
}
});
Please just add click listener in adapter like as follows
mView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
Related
I don't know how to set the selected country isd code in
spinner.Below I have posted the code what I have been tried so far:
MainActivity.java:
public class MainActivity extends Activity implements OnItemSelectedListener {
ArrayList<String> arrCode;
ArrayList<String> arrCountry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
arrCode = new ArrayList<>();
arrCountry = new ArrayList<>();
arrCountry.add("US");
arrCountry.add("KZ");
arrCountry.add("EG");
arrCountry.add("ZA");
arrCountry.add("GR");
arrCode.add("1");
arrCode.add("7");
arrCode.add("20");
arrCode.add("27");
arrCode.add("30");
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrCountry);
adapter_state.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_mobile_code.setAdapter(adapter_state);
sp_mobile_code.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
int spinnerValue1 = sp_mobile_code.getSelectedItemPosition();
String data = arrCode.get(spinnerValue1);
Log.e("data", "" + data);
sp_mobile_code.setPrompt(data);
/* sp_mobile_code.setSelection(position);*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
My issue is : I can't set the isd code in same spinner.If I have to
set isd code in textview means it will be easy.But I have to set it
in the spinner
Edit: spinner list showing correctly the country list.on clicking the country list, I have to show the isd code
Use Custom ArrayAdapter.
private static class CustomSpinnerAdapter extends ArrayAdapter<String>
{
List<String> arrCodes;
public CustomSpinnerAdapter(Context context, int resource, List<String> items, List<String> arrCodes)
{
super(context, resource, items);
this.arrCodes = new ArrayList<>();
this.arrCodes = arrCodes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
TextView view = (TextView) super.getView(position, convertView, parent);
view.setText(arrCodes.get(position));
return view;
}
}
Check the position in the getView() and set text of your desire. Use this adapter for the Spinner
I've been trying to make listView redirect user onClick to URL's when clicking on different elements.
Example:
clicking on "apple" would open "stackoverflow.com",
but clicking on tomato would open "google.com" etc.
Could anyone give me some advice how can I accomplish this, because after 2 days of trying and searching all I've got is a headache..
displayMainMenu.java
public class DisplayMainMenu extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_main_menu);
final String[] food = new String[] {"Apple", "Tomato", "Potato"};
ListAdapter adapter = new MyAdapter(this, food);
ListView listView = (ListView) findViewById(R.id.mainMenu);
listView.setAdapter(adapter);
}
class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, String[] values)
{
super(context, R.layout.entry, values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.entry, parent, false);
String text = getItem(position);
TextView textView = (TextView) view.findViewById(R.id.listTextView1);
textView.setText(text);
return view;
}
}
}
You should make a new class that holds the shown string value (Apple, Tomato, Potato, etc) and also holds the URL that you want to link to.
Then make the ArrayAdapter use that class. The getView function you have already should suffice (when its updated to use the new class).
Then in your activity, use 'setOnItemClickListener' to set a new listener.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyItem clickedItem = () parent.getItemAtPosition(position);
<< Insert code to open the link with the URL you can get from 'clickedItem' >>
}
});
That should do it.
I am aware that there are plenty of similar questions, but they all have in common, that their solutions dont work with my list :(
I am trying to get my userList refreshing itself via the custom ArrayAdapter, when the database-contents are changed. In my case when i reset();
here my snippets (partial code):
MainActivity.java
public class MainActivity extends ListActivity {
private MyUserListAdapter myUserlistAdapter;
public ArrayList<User> myUserList = new ArrayList<User>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//shortened the list-filling. but it works properly!
User user = db.readUser(int);
myUserList.add(user);
myUserlistAdapter = new MyUserListAdapter(this, R.layout.row_main, myUserList);
setListAdapter(myUserlistAdapter);
//now when reset-button is hit, the listview should refresh itself
bReset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//this is what is posted in most questions, but it does nothing for me
//myUserlistAdapter.notifyDataSetChanged();
//getListView().invalidateViews();
} });
and here myUserListAdapter.java:
public class MyUserListAdapter extends ArrayAdapter<User>{
private Context context;
private ArrayList<User> userList;
public MyUserListAdapter(Context context,
int textViewResourceId, ArrayList<User> userList) {
super(context, textViewResourceId, userList);
this.context = context;
this.userList = userList;
}
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.row_main, null);
}
User user = getItem(position);
TextView tvUser = (TextView) v.findViewById(R.id.tvUser);
ImageView ivVoted = (ImageView) v.findViewById(R.id.ivVoted);
tvUser.setText(user.getName());
//abfrage ob hasVoted() = true muss noch eingebaut werden.
if (user.getVoted().equals("1"))
ivVoted.setImageResource(R.drawable.redcheck);
else
ivVoted.setImageResource(R.drawable.greencheck);
return v;
}
}
User.java is just a simple object-class. think its not the troublemaker here!
any help is appreciated!!! thx :-)
I am trying to get my userList refreshing itself via the custom
ArrayAdapter, when the database-contents are changed.
Since you are using ArrayAdapter and not CursorAdapter when you update data in database your adapter won't refresh itself. Whenever you want to update ListView you need to provide new datasource for Adapter.
One possible solution is to create setter in adapter subclass that will change datasource of adapter.
Pseudo code:
/* setter in adapter subclass */
public void changeDataSource(ArrayList<User> newUserList) {
this.userList = newUserList;
}
Then call adapter.notifyDataSetChanged(); for ListView update.
Try this:
arrayAdapter.clear()
for(Object o : objects)
arrayAdapter.add(o)
clear() and add() call to notifyDataSetChanged() itself.
I have an Android application with a ListView in it, the ListView will setup fine but now I want a image in the ListView to be clickable. I do this by using 2 classes, the Activity class (parent) and an ArrayAdapter to fill the list. In the ArrayAdapter I implement a OnClickListener for the image in the list that I want to be clickable.
So far it all works.
But now I want to run a function from the activity class when the onClick, for the image in the list, is run but I do not know how. Below are the 2 classes that I use.
First the Activity class:
public class parent_class extends Activity implements OnClickListener, OnItemClickListener
{
child_class_list myList;
ListView myListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// setup the Homelist data
myList = new child_class_list (this, Group_Names, Group_Dates);
myListView = (ListView) findViewById(R.id.list);
// set the HomeList
myListView.setAdapter( myList );
myListView.setOnItemClickListener(this);
}
void function_to_run()
{
// I want to run this function from the LiscView Onclick
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// do something
}
}
And the ArrayAdapter from where I want to call a function from the Activity class:
public class child_class_list extends ArrayAdapter<String>
{
// private
private final Context context;
private String[] mName;
private String[] mDate;
public child_class_list (Context context, String[] Name, String[] Date)
{
super(context, R.layout.l_home, GroupName);
this.context = context;
this.mName = Name;
this.mDate = Date;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.l_home, parent, false);
ImageView selectable_image = (ImageView) rowView.findViewById(R.id.l_selectable_image);
selectable_image.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// I want to run the function_to_run() function from the parant class here
}
}
);
// get the textID's
TextView tvName = (TextView) rowView.findViewById(R.id.l_name);
TextView tvDate = (TextView) rowView.findViewById(R.id.l_date);
// set the text
tvName.setText (mName[position]);
tvDate.setText (mDate[position]);
return rowView;
}
}
If anyone knows how to run the function in the activity class from the arrayadapter or how to set the image onClickListener in the Activity Class I would greatly apriciate the help.
Inside onClick() Do something like this:
((ParentClass) context).functionToRun();
Just for clarity to expand on provided answers
In a BaseAdapter you can get the parent class by calling this.getActivity();If you then typecast this to the actual activity class you can then call a function as per #AdilSoomro answer below so you actually end up with something like this
public class MyAdapter extends BaseAdapter<Long> {
public MyAdapter(Activity activity,
TreeStateManager<Long> treeStateManager, int numberOfLevels) {
super(activity, treeStateManager, numberOfLevels);
}
#Override
public void handleItemClick(final View view, final Object id) {
((MyActivity) this.activity).someFunction();
}
}
Then just declare someFunction in MyActivity to do what you want
protected void someFunction(){
// Do something here
}
I am creating a contact list view, diplaying user name,user email and user id. Now while clicking on particular item i want to post some event to server based on the user id. How to get the user id inside the onClickItem listener, as user id is long value. i am able to get the user name that means the text but not the user id.
listView has onCLicklistener that has parameter position.If you are using arrayList to inflate ListView then you can use this positon to get corresponding object.
You can try to set the user id to tag using View.setTag and View.getTag. There are two version available choose the one you need. This way you can attach the user id as tag and then get it back.
http://developer.android.com/reference/android/view/View.html#setTag(int, java.lang.Object)
You code should look like:
view.setTag(Long.valueOf(id));
.....
onClickListener(..) {
Long id = (Long)view.getTag();
}
You should make your own bean class which contains your userid and put it in List (or ArrayList)
then create an adapter by creating a class extending ArrayAdapter (for instance) to bind your list of this bean class
register a listener either using onItemClickListener or View listener in your row if you inflate your custom layout.
get the position and use it to retrieve your userid on your bean list.
Here's my snippet
public class ListActivity extends Activity implements OnItemClickListener {
private Context context;
private RowAdapter adapter;
private ArrayList<Row> rowList = new ArrayList<Row>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = ListActivity.this;
initRows();
adapter = new RowAdapter(context, rowList);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
private void initRows() {
Row row = new Row(1);
rowList.add(row);
row = new Row(2);
rowList.add(row);
}
public class Row {
long userid = 0;
public Row(long userid) {
this.userid = userid;
}
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
}
public class RowAdapter extends ArrayAdapter<Row> {
private Context context;
public RowAdapter(Context context, ArrayList<Row> bindList) {
super(context, R.layout.row_layout, bindList);
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, null);
}
//if you use some additional View you can retrieve your position using this
Button button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateSelected(position);
}
});
return view;
}
}
//or if you rather just listen on row click then you can retrieve your position using this
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
updateSelected(position);
}
private void updateSelected(int position) {
rowList.get(position).getUserid();
//have it your way
}
}