How to make AdapterView.OnItemClickListener() work, when
... activity implements View.OnLongClickListener, View.OnClickListener,
DragDropPresenter,
View.OnTouchListener { ... }
and I there is
public void onClick(View v) {
// TODO Auto-generated method stub
}
to handle clicks?
Idea is that drag and drop is activated on a long click, and the OnItemClickListener method is used on a short click. Is it even possible?
Your question is a bit simplified but I hope that the example below will be helpful:
public class MainActivity extends Activity implements OnClickListener, OnItemClickListener, OnItemLongClickListener {
....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
.....
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(this);
listView.setOnItemClickListener(this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
.....
}
#Override
public boolean onItemLongClick (AdapterView<?> parent, View item, int position, long id) {
....
}
I overcame the problem of handling short clicks by assigning each cell a tag and then reading the tag with the simple onClick listener:
public void onClick(View v) {
Integer position = (Integer)v.getTag();
if (position = ...){ do some stuff }
}
Related
I have an activity Advanced Research, with a spinner that contains all category from my db. When i create the activity, this spinner call onSetItemListener in loop. Why?
I try to use onTouchListener but not working, maybe i fail something.
if(risultato.getCategoria().getSottocategorie().toArray() != null && risultato.getCategoria().getSottocategorie().toArray().length != 0){
adapterSpinnerCategoria = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, risultato.getCategoria().getSottocategorie().toArray());
}else{
adapterSpinnerCategoria = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, categoriaVuota);
}
spinnerCategoria.setAdapter(adapterSpinnerCategoria);
public void spinnerChange(AdapterView<?> parent){
if(!parent.getSelectedItem().toString().equals("Sottocategorie vuote")) {
ricercaAvanzata.setCategoria((Categoria) parent.getSelectedItem());
setArticoli();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinnerChange(parent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
return;
}
public void setListener() {
spinnerCategoria.setOnItemSelectedListener(this);
}
public class ActivityRicercaAvanzata extends AppCompatActivity implements AdapterView.OnItemSelectedListener { .... }
I expect that when i click on spinner call onItemSelected not before
i am using Spinner for Country Selection for User Registration.
please vote my answer.
Spinner spcountry;
String country;
//in onCreare
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spcountry = (Spinner) findViewById(R.id.country);
final String[] countryNames = getResources().getStringArray(R.array.countries_array);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, countryNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spcountry.setAdapter(aa);
spcountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
if (position == 0) {
return;
} else
country = countryNames[position];
//Toast.makeText(getBaseContext(),country,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
From what I can see, you are extending AdapterView.OnItemSelectedListener.
You cannot extend it since OnItemSelectedListener is an interface, not a class.
What you actually should be doing is, implementing it instead, like so:
MyActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
}
Then you can set the OnItemSelectedListener on the Spinner,
spinnerCategoria.setOnItemSelectedListener(this);
And the final step would be to write the implementation for the overridden methods,
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Your implementation here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//Your implementation here
}
Ok, mark as solved thx. I create a new List and i convert my set into list. After this operation i add a null element at first position, and when i'm call onItemSelected, i do
if(position != 0)then
//do something
Activity start always at position 0 then must wait my click and my choice. Thx all for help me.
I'm using the tabbed layout (with swipe).
Here I have 3 tabs with controlled by a SectionsPagerAdapter. Each tab is a ListFragment.
Now I want to get an event fired when one of the items in the list is clicked. I would like a listener for each tab.
Here's the code now (Which isn't working, event is not fired).
public class NyhederFragment extends ListFragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private static final String TAG="NyhederFragment";
private List<Item> newsItems;
private ArrayList newsHeadlines;
private ArrayAdapter adapter;
private BroadcastReceiver updateReciever;
public NyhederFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ListView newsList = new ListView(getActivity());
newsList.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
newsList.setId(R.id.list);
DatabaseHelper dbConn = new DatabaseHelper(getActivity());
newsItems = dbConn.getAllItemsFromNews();
newsHeadlines = new ArrayList();
for(Item i : newsItems){
newsHeadlines.add(i.getTitle());
}
adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, newsHeadlines);
setListAdapter(adapter);
newsList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("debug", "single click");
}
});
dbConn.close();
getActivity().registerReceiver(updateReciever, new IntentFilter("ArticlesUpdated"));
return newsList;
}
}
What is it, I'm doing wrong?
Thanks a lot in advance!
If you are using ListFragment then you can simply use its override method onListItemClick()
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
It is due to custom list item. The default focus is with custom list item (button/textview). It causes this issue.
Please add android:descendantFocusability="blocksDescendants" in root layout of list element.
Hope this will help someone.
change setListAdapter(adapter); to newsList.setAdapter(adapter);
If you wanted to create or re-use or an existing handler that implements AdapterView.OnItemClickListener, rather than implementing onListItemClick() within the ListFragment, you can do so by getting a reference to the ListView of the ListFragment and setting its listener. In your ListFragment.onResume() you could do:
#Override
public void onResume() {
super.onResume();
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("TAG", "Stop touching me");
}
});
}
In my case, I can use the same listener from an Activity with a ListView, a ListActivity or a ListFragment, e.g.
listView.setOnItemClickListener(new MyListViewOnClickListener(getActivity()));
I have a button and a list view. I am setting three adapter in one listview as per click on list but when I press back button it will click only one time.
The code is here:
public class GamesFragment extends ListFragment{
Context context;
Dialog dialog;
Game_Adapter gameadapter;
Game_Channels_Sections_Adapter GameChannelsSections;
Game_Sections_Details_Adapter GameSectionsDetails;
ListView listView1;
JSONArray dataJsonObject;
Button back,back2;
TextView title;
Button add;
int i=0;
int y=0;
int z=0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.game_list, container,false);
listView1=(ListView)view.findViewById(android.R.id.list);
back=(Button) view.findViewById(R.id.button_back);
GamesFragmentData dataobserver=new GamesFragmentData();
add=(Button) view.findViewById(R.id.button_add);
title=(TextView) view.findViewById(R.id.textview_caption);
title.setText("Games");
add.setVisibility(View.INVISIBLE);
ServerManager.getInstance().addObserver(dataobserver);
ServerManager.getInstance().readLoopForGameData(AppConstances.Games_Channels);
if(gameadapter==null)
gameadapter=new Game_Adapter(getActivity(), new JSONArray());
listView1.setAdapter(gameadapter);
Log.e("","In ongameadapter---->");
return view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
System.out.println("In onListItemClick---->");
Log.e("","In onListItemClick---->");
ServerManager.getInstance().readLoopForGame_Channels_Sections_Data(AppConstances.Games_Channels_Sections);
GameChannelsSections=new Game_Channels_Sections_Adapter(getActivity(),new JSONArray());
listView1.setAdapter(GameChannelsSections);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("","In onListItemClick1---->");
listView1.setAdapter(gameadapter);
}
});
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
ServerManager.getInstance().readLoopForGame_Channels_Sections_Details_Data(AppConstances.Games_Sections_Details);
GameSectionsDetails=new Game_Sections_Details_Adapter(getActivity(),new JSONArray());
listView1.setAdapter(GameSectionsDetails);
}
Log.e("","In onItemClick---->");
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("","In onItemClick1---->");
listView1.setAdapter(GameChannelsSections);
}
});
}
});
super.onListItemClick(l, v, position, id);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
The code has two method:
onListItemClick
onItemClick
When I click on list view control, it goes from onListItemClick to onItemClick because I am setting three adapter in single list view on onclick.
But when I click back button, I need to take back. I cannot go back.
Say, if I press on adapter 1, I set adapter 2 AND if I press adapter 2, I have set adapter 3.
Now, I am at adapter 3. On click of back button, I go back from 3 to 2 but I cannot go from 2 to 1.
In short how can I go control back from onItemClick to onListItemClick so that the flow of clicking can be repeated?
If I have 2 or more listviews in one activity,then how do I use a onclicklistener? I mean How do I know on which one of them the user click?
public void onItemClick(AdapterView parent, View v, int position, long id) {
}
The above code is what I used,however when I try to use another listview,I just can't find a way to detect which listview is clicked.
Any ideeas to solve this?
In this case, the parent is the listView from which the itemClick originated. So what you can do is keep a member variable for each ListView and compare the parent to those members to see which list triggered the click.
So here's a simple class with what I mean:
public class MyTest extends Activity{
private ListView list1;
private ListView list2;
public void onCreate(Bundle b){
super.onCreate(b);
list1 = new ListView();
list2 = new ListView(); //or findViewById if you declared them in your layout
//the rest of your creation code here
}
public void onItemClick(AdapterView parent, View v, int position, long id) {
if(list1 == parent){
//handle list1 click
}else{
//handle list 2 click
}
}
}
There are two ways you can do it.
Implement OnItemClickListener
public class ListViewTest extends Activity implements OnItemClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
if(view ==myListView)1{
}
if(view ==myListView){
}
}
}
Set your own listener
myListView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on second listview
}
});
You can do it as this:
listView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on first listview
}
});
listView2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on second listview
}
});
its pretty simple ,
only one list can act as the official list under a ListActivity and this list (and only this list) should have the special list id (#android:list i think) so just set the id of the other list to some other id and set its setOnItemClickListener to do whatever you want. I currently work on an app with 2 listViews and an additional list Fragment.
My activity has a ListView that has a custom ArrayAdapter.
On my ArrayAdapter i have an image, a bunch of textboxes and a button.
On the getView of the adapter i get my button and set setOnClickListener. From the click listener i can get the index of the clicked item.
Now my problem is that i want to propagate that information to my main activity, where i want to handle my button click.
I can save the index information in a static var, but i still don't know how to fire an event in my activity.
How do i do that?
I'm 6 days new to Android so, thanks
iggy
Code:
My Activity:
public class MyClass extends Activity{
...
public void onCreate(Bundle savedInstanceState) {
...
myListView = (ListView)findViewById(R.id.lvxml);
myList = new MyCustomArrayAdapter(this, myAnotherClassObject);
myListView .setAdapter(myList);
...
}
}
Now in my Adapter
public class MyCustomArrayAdapter extends ArrayAdapter<myAnotherClass> {
...
....
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button b = (Button)convertView.findViewById(R.id.myButtonInListView);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doStuff;
}
});
}
}
I need to somehow fire a buttonclick from my main activity, but without loosing the possibility to read the index clicked in the list view.
Here's an alternative and, what I think to be, more elegant solution.
Firstly, in your MyCustomArrayAdapter class, define an interface:
public interface MyCustomRowButtonListener{
void onCustomRowButtonClick(MyAnotherClass selectedItem, int position, View view);
}
Create an member variable of MyCustomRowButtonListener in your ArrayAdapter
public class MyCustomArrayAdapter{
private MyCustomRowButtonListener mRowButtonListener;
//....
}
and add a parameter for the listener in the constructor
public MyCustomArrayAdapter(Context context, MyCustomRowButtonListener listener){
mContext = context;
mRowButtonListener = listener;
}
in the getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button b = (Button)convertView.findViewById(R.id.myButtonInListView);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mRowButtonListener.onCustomRowButtonClick(getItem(position),position,b);
}
});
}
and in your activity:
myList = new MyCustomArrayAdapter(this, myAnotherClassObject,this);
Now let your activity implement MyCustomRowButtonListener
public class MyClass extends Activity implements MyCustomRowButtonListener{
...
public void onCreate(Bundle savedInstanceState) {
...
myListView = (ListView)findViewById(R.id.lvxml);
myList = new MyCustomArrayAdapter(this, myAnotherClassObject,this);
myListView .setAdapter(myList);
...
}
}
public void onCustomRowButtonClick(MyAnotherClass selectedItem, int position, View view){
Toast.makeText(this,"You have selected "+selectedItem,Toast.LENGTH_SHORT).show();
}
So I've solved it somehow. It's probably not the way to do it but it works.
I save my activity in a static var.
Button b = (Button)convertView.findViewById(R.id.myButtonInListView);
b.setTag(position);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int i = (Integer) v.getTag();
myStaticVarRep.myActivity.myMethod(i);
}
});
The index ist the position variable.
Ist has to be final to use it here
public View getView(final int position, View convertView, ViewGroup parent)
You can inform your Activity with a listener-interface.
I'm going to assume your code looks a little like this.
public class <Your Class> ... implements OnClickListener{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
.
button.setOnClickListener(this);
}
}
To handle button click events, you need to have an onClick method that looks like this.
public void onClick(View v){
<Handle your button click in here>
}
Whenever you click your button, it'll invoke the onClick method. That is where you would manipulate your static var, fire off other methods, etc. I hope that helps.