Android listview clicking on item multiple times - android

I have a listview with several items. When clicking on an item, an Activity is opened. However, when I click fast several times on the item, the activity, asociated with it, is opened several times. How to open the item only once?
I use the following code:
private OnItemClickListener newsfeedClickHandler = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyObject newsfeed = adapter.getItem(position);
onNewsfeedClick(newsfeed);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newsfeed, container, false);
...
listView = (ListView) view.findViewById(R.id.newsfeeds);
listView.setOnItemClickListener(newsfeedClickHandler);
listView.setAdapter(adapter);
...
return view;
}
private void onNewsfeedClick(MyObject newsfeed) {
Intent intent = createIntent(newsfeed);
startActivity(intent);
}

The correct way to prevent calls to the ListView items would be to (obviously) disable the OnItemClickListener:
private void onNewsfeedClick(MyObject newsfeed) {
listView.setOnItemClickListener(null);
Intent intent = createIntent(newsfeed);
startActivity(intent);
}
Re-set the listener at onResume, when this activity is visible again.
#Override
protected void onResume() {
super.onResume();
listView.setOnItemClickListener(newsfeedClickHandler);
}

Maintain a boolean value say isItemClicked and reset it when you return back to the listview.
private boolean isItemClicked;
private OnItemClickListener newsfeedClickHandler = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!isItemClicked) {
isItemClicked = true;
MyObject newsfeed = adapter.getItem(position);
onNewsfeedClick(newsfeed);
}
}
};
private void resetIsItemClicked() {
isItemClicked = false;
}

To prevent multiple clicks on ListView Items, add the following code in your listview click listener:
if (SystemClock.elapsedRealtime() - mLastClickTimeListViewItem < 1000){
return;
}

Related

Getting item position 0 when clicking an item in ListView

I am trying to send an item position from a Fragment to an Activity, but I always get invoiceId 0 every time I select an item in listView.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent seperateView = new Intent(rootView.getContext(),SeperateViewForDeliveryList.class);
seperateView.putExtra("invoiceId", listView.getItemAtPosition(position).toString());
startActivity(seperateView);
}
});
listView.setAdapter(deliveryListAdapter);
return rootView;
In activity class
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seperate_view_for_delivery_list);
invoiceId = getIntent().getExtras().getString("invoiceId");
Toast.makeText(this, "invoiceID " + invoiceId, Toast.LENGTH_SHORT).show();
}
Use this
seperateview.putExtra("invoiceId",String.valueOf(position));
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent seperateview=new Intent(rootView.getContext(),SeperateViewForDeliveryList.class);
seperateview.putExtra("invoiceId",parent.getItemAtPosition(position).toString());
startActivity(seperateview);
}
});
listview.setAdapter(deliveryListAdapter);
return rootView;
Try this
getItemAtPosition returns an object of the data associated with the specified position in the list, while position itself is what you want.
Change your code to
seperateView.putExtra("invoiceId", String.valueOf(position));
We can also pass integer value in an Intent. Try this:
seperateview.putExtra("invoiceId",listview.getItemAtPosition(position));
getIntent().getIntExtra("invoiceId",0);

Clicking on each item of listview in a fragment is not working

I have a listview and want to set an onClickListener on each item in this fragment but it's not working.I also wanted to set a contextMenu on the listview and that's not working either.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
purchasedItemsView = inflater.inflate(R.layout.purchased_items_fragment , container, false);
db = new StoreDataBase(getActivity() , Consts.StoreDB.DB_NAME , Consts.StoreDB.DB_VERSION);
storeArrayList = new ArrayList<>();
listView = (ListView) purchasedItemsView.findViewById(R.id.storeListView);
adapter = new StoreListViewAdapter(getContext() , R.layout.store_item_row , storeArrayList);
listView.setAdapter(adapter);
adapter .notifyDataSetChanged();
registerForContextMenu(listView);
sendData(purchasedItemsView);
return purchasedItemsView;
}
private void sendData(View view){
Bundle bundle = getArguments();
if (bundle != null) {
final String[] names = bundle.getStringArray(Constc.Data.names);
listView = (ListView) view.findViewById(R.id.storeListView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
}else{
}
}
Don't reinitialize listview after you have done it once in onCreateView(). Therefore, remove this line from sendData() method:
// remove this
listView = (ListView) view.findViewById(R.id.storeListView);
Then you need to move this part of code outside of if statement or inside of onCreateView() method.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
Point 1:
Seems your array list is empty, so fill some data
storeArrayList = new ArrayList<>();
//-------------------------------------
Bundle bundle = getArguments();
if (bundle != null) {
final String[] names = bundle.getStringArray(Constc.Data.names);
if(names != null && names.length() > 0) {
storeArrayList.addAll(names);
}
}
//-------------------------------------
listView = (ListView) purchasedItemsView.findViewById(R.id.storeListView);
adapter = new StoreListViewAdapter(getContext() , R.layout.store_item_row , storeArrayList);
listView.setAdapter(adapter);
Point 2: You don't need "notifyDataSetChanged();" right after you set the adapter.
//adapter .notifyDataSetChanged();
Point 3:
Use long click listener for showing context menu
listView.setOnItemLongClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "long press clicked");
//show dialog or context menu dialog.
}
});
Point 4:
comment the sendData method and use the onclick directly
//sendData(purchasedItemsView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
Hope this helps.
Vote Up - If you like it.

Select spinner without triggering listener

Long version I have two spinners on my screen and when I select the one, I do certain operations, and the other spinner should display the original selection, because of design patterns. In this situation, I let the user select the elements on a list by year, and by state. You would agree with me that when the user choose to select by year, the spinner regarding the state should display the default selection (the one that displays all of the item) and not the last selected one.
I am trying to do this from this morning, but when I found this solution I really though I was done.
Short version I want to setSelection(0) on the spinner which is not clicked, without triggering its listener (which by the way, will setSelection(0) on the first spinner, if triggered)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// irrelevant code...
mYearSpinner.setOnItemSelectedListener(onYearSelected);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
// irrelevant code...
}
private AdapterView.OnItemSelectedListener onYearSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mStateSpinner.setOnItemSelectedListener(null);
mStateSpinner.setSelection(0);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
// Do something...
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
private AdapterView.OnItemSelectedListener onStateSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mYearSpinner.setOnItemSelectedListener(null);
mYearSpinner.setSelection(0);
mYearSpinner.setOnItemSelectedListener(onYearSelected);
// Do something...
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
But no! The listeners will just fire, indiscriminately.
Is there someone who knows how to handle this problem?
Why this solution wouldn't work?
As requested, here is the full code of my onCreateView(...) method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Log.d(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_career, container, false);
mExamListView = (ListView) view.findViewById(R.id.exam_list_view);
mYearSpinner = (Spinner) view.findViewById(R.id.select_by_year_spinner);
mStateSpinner = (Spinner) view.findViewById(R.id.select_by_state_spinner);
mLoadingView = view.findViewById(R.id.fragment_career_loading_spinner);
mExamListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Exam exam = (Exam) parent.getItemAtPosition(position);
if (exam.isBookable()) {
FragmentManager fm = getActivity().getSupportFragmentManager();
SessionsDialogFragment.newInstance(exam).show(fm, null);
}
}
});
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> yearAdapter = ArrayAdapter.createFromResource(getActivity(),
R.array.spinner_year, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
yearAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> stateAdapter = ArrayAdapter.createFromResource(getActivity(),
R.array.spinner_state, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mYearSpinner.setAdapter(yearAdapter);
mStateSpinner.setAdapter(stateAdapter);
mYearSpinner.setOnItemSelectedListener(onYearSelected);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
return view;
}
I tried implementing what --- suggested and I want to report here what happens.
When the application starts all the two listeners are executed only once.
Then, if I select an item on the first spinner (let's say the year spinner), the expected listener is executed only once (as it should be), and so it is, if I keep selecting items on it.
Ultimately, if I select and item on the state spinner, the listeners are executed in this way
1. onStateListener
2. onYearListener
3. onStateListener
From reading your comments it sounds like you want to set the selection of a second spinner to 0 from your first spinners onItemClick method without triggering its listener.
If you keep a record of the old position the spinners are at in integer variables we can check if the position has changed and only run the code if it has.
That way if we set the old position variable to 0 before changing the spinners current position to 0 it will think its position hasn't changed and so won't run the code in the listener.
private AdapterView.OnItemSelectedListener onYearSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (lastYearPosition != position) {
//Do you code here
lastStatePosition = 0;
mStateSpinner.setSelection(0);
}
lastYearPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
private AdapterView.OnItemSelectedListener onStateSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (lastStatePosition != position) {
//Do your code here
lastYearPosition = 0;
mYearSpinner.setSelection(0);
}
lastStatePosition = position;
}

ListFragment onItemClickListener not working

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()));

how can i call from onItemClick to onListItemClick method in android

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?

Categories

Resources