How to trigger onListItemClick in a ListFragment - android

In the tablet layout of my app, I have three ListFragments and one regular Fragment, let's call them Make, Model, Size, and Details. Initially the Make list is populated, then based on the Make selection, the Model list is populated; when a Model is selected, the Size list is populated; when a Size is selected, Details are shown. Each of these events (list item selection) is handled through the onListItemClick handler.
On startup, I want to populate the Make list, select the first Make in the list and have it go through the onListItemClick handler to populate the Model list (and so on so that all lists are populated and the details are shown - this should also be the behavior when any selection is made in any of the lists - select the first item in the next list until we get to showing the details). Note that I have control of the DB and for every Make there will always be at least one Model, for each Make/Model at least one Size, for each Make/Model/Size exactly one Detail.
So, I want to select the first item in the list and have it trigger the onListItemClick handler. I've tried the following (with appropriate bounds checking, etc), but it doesn't work.
getListView().setItemChecked(0, true);
The only changes to an "out of the box" ListFragment are to set the CacheColorHint as such
getListView().setCacheColorHint(R.color.GhostWhite);
where GhostWhite is set in the styles.xml as
<color name="GhostWhite">#88FFFFFF</color>
Any ideas?
Thanks in advance.

To select the first item in the list, first get focus from touch, then select the first item, then trigger the onclick handler
int position = 0;
getListView().requestFocusFromTouch();
getListView().setSelection(position);
getListView().performItemClick(getListView().getAdapter().getView(position, null, null), position, position);

Try setSelection(int position)
http://developer.android.com/reference/android/widget/ListView.html#setSelection(int)

1.) In the OnActivityCreated of your list fragment create an interface like so
public interface ListItemSelectedListener {
public void onListItemSelected(int index);
}
2.) Implement the interface in your activity
3.) Create private ListItemSelectedListener selectedListener in your list fragment
4.) Set selectedListener.onListItemSelected(0) in the OnActivityCreated.
This is how it worked for me using the Android Support Package - should be similar on HC

Try adding this,, it works in my project:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Intent intent = new Intent();
intent.setClass(getActivity(), someActivity.class);
startActivity(intent);
}

in The Fragment class in onActivityCreated(Bundle savedInstanceState) method, you can add the following:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//if the parent is in the landscape, make the first item selected
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
try {
if (mItems.size() > 0) {
//notify the activity that an item is selected
mListener.onMasterItemSelected(mItems.get(0));
}
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
}

Related

Disable onItemClickListener for one list?

I've two list one with custom adapter and other with array adapter. So i want onItemClickListener to work with custom adapter listview and it will automatically disable when I start using same listview for array adapter. To initiate array adapter list I'm using button.
I've already try using ListView.setClickable(false)
. but this doesn't work.
If setClickable(boolean) not working then u can use flag to work with as per your behavior.It'll work as u want.
Inside the onitem click event put in an if condition, that is, if its the button to enable the click then perform operations, otherwise do not.
In the onClick of button1 set a integer flag to 1 & of button2 set flag to 2
Then define onItemClickListener like this
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(flag ==1){
Toast.makeText(getApplicationContext(),"You selected "+ arr.get(position)+"", 1).show();
Intent ints= new Intent(getApplicationContext(),Activity2.class);
ints.putExtra("pos", position);
startActivity(ints);
}
}
NOTE: if the flag is not 1 then dont implement the required code thus by providing a condition you manipulate the onClick of listview.

ListeView recycling Views causing problems

When I click a list item, every 12th item is also selected. ListViews recycle views and therefore many items are being selected, any idea how I overcome the problem so just the items I click are marked as checked.
#Override
public void onListItemClick(ListView l, View v, int position, long id){
CheckedTextView check = (CheckedTextView) v;
if (check.isChecked()){
check.setChecked(false);
selections.remove((Integer) position);
}
else{
check.setChecked(true);
selections.add((Integer) position);
}
}
I use an ArrayAdapter. Names is a String[] of about 1000 options.
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_multiple_choice, names);
setListAdapter(adapter);
As this answer CheckBox in ListView says maintain a list of your checked items and then check your CheckBox in getView based on that list.
Also set the onCheckedChangeListener for that CheckBox null before checking it or else the corresponding listener will be called.
In lisview, recycling is very tricky concept, first by recycled view android means view which were used earlier, so basically this view will contain all the parameter which you or user set earlier.
This view is now returned to your adapter, what you do is to check if its null inflate a new view set new values supply it back, if its not then refresh the widgets view contains with new values and then supply it back.
Now coming back to your code, you are simply checking if this view was checked or not, say suppose you checked first view in you list, now when you scroll down further this same view will be returned to you through recycling and guess what it will be checked again, remember it was the same first view you used, this is reason for your problem for founding a unchecked view checked.
Now to your resolution, maintain a separate list somewhere globally to hold on checked index, and from your adapter just check or uncheck the checkbox before sending it to list depending about its index presence in maintained list. this will resolve your probelm.
Please try something like this.
-- Have a static HashMap on your main activity.
--Implement two methods over you activity, AddSelection and RemoveSelection
--On your adapter, implement onCheckedStateChanged listener and, perform either addition or deletion from the map, based on position in list.
In Your Activity:
private static HashMap<Integer,Integer> selectedPositions = new HashMap<Integer,Integer>();
public static boolean isSelected(int position){
System.out.println("#### Position: " + position + " Value: " + selectedPositions.containsKey(position));
return selectedPositions.containsKey(position);
}
public static void addSelection(int position){
System.out.println("#### Puttin Position: " + position);
selectedPositions.put(position,position);
}
public static void removeSelection(int position){
System.out.println("#### Removing Position: " + position);
selectedPositions.remove(position);
}
In your adapter:
checkbox.setChecked(MainActivity.isSelected(position));
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton view, boolean state) {
// TODO Auto-generated method stub
if(state == true){
MainActivity.addSelection(position);
}else{
MainActivity.removeSelection(position);
}
}
});
thats it now, whenever you want iterate through the hasmap for finding out selected items, make sure you clear it when job is done, else u will end up piling selected positions again and again.

Automatic click on ListView if has only one item

I am trying to search for some data in Mysql database, then display it Listview
When more than 1 result is found, clicking on any one of them will take you to its respective details page.
But.. I am looking to go to details page directly if there is only one result in list view. Put simply, how would I call onItemClick on the list view automatically when there is only one item in the list.
My Listview's onClickItemListener looks like this:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// when a student is selected then the following methods are called
DetailsFragment.setLUNCH_TYPE(searchResult.get(position).lunchtype);
Log.d("Lunch type selected", ""+DetailsFragment.getLUNCH_TYPE());
((HomeActivity) getActivity()).startStudentSale(searchResult
.get(position).name.toString(),searchResult
.get(position).isStudent,searchResult.get(position).id);
// it was comming null here when running this this need to find out why
// ((HomeActivity)getActivity()).setmSaleType(SALE_TYPE.SEARCHED_STUDENT);
}
When you know the count of the resultSet, say cnt and if it is 1, i.e.
if(cnt==1){
Intent intent=new Intent(getApplicationContext(),DetailActivity.class);
startActivity(intent);
}

How to change other items in a Android ListView when one item is clicked

I have a ListView that contains items with checkboxes that should behave sometimes like a CHOICE_MODE_MULTIPLE and sometimes like a CHOICE_MODE_SINGLE. What I mean is for certain items in the list, when selected certain other items needs to be deselected whilst other can remain selected.
So when item A is checked I can find in my data the item B that needs to be unchecked but how do I get the UI to refresh to show this as I (I believe) cannot find the actual View that represents B but just it's data?
It sounds like you're off to a good start. You're right that you should be manipulating the underlying data source for item B when A is clicked.
Two tips that may help you:
Your getView() method in the Adapter should be looking at your data source and changing convertView based on what it finds. You cannot find the actual View that represents B because in a ListView, the Views are recycled and get reused as different data needs to be displayed. Basically, when an item is scrolled off the list, the View that was used gets passed to the getView() function as convertView, ready to handle the next element's data. For this reason, you should probably never directly change a View in a ListView based on user input, but rather the underlying data.
You can call notifyDataSetChanged() from within your adapter to signal that somewhere the underlying data has been changed and getView() should be called again for the elements currently displayed in your list.
If you're still having trouble, feel free to post some code that illustrates the specific problem that you're having. It's much easier to provide concrete advice when the problem is better defined. Hope this helps!
you can use singleChoice alartDialog, i have used like:
private int i = 0; // this is global
private final CharSequence[] items = {"Breakfast", "Lunch", "Dinner"}; // this is global
Button settings = (Button)view.findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
//Title of Popup
builder.setTitle("Settings");
builder.setSingleChoiceItems(items, i,
new DialogInterface.OnClickListener() {
// When you click the radio button
public void onClick(DialogInterface dialog, int item){
i=item;
}
});
builder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (i == 0) {
//it means 1st item is checked, so do your code
}
if (i == 1) {
//it means 2nd item is checked, so do your code
} /// for more item do if statement
}
});
//When you click Cancel, Leaves PopUp.
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
});
i have initialized i=0, so that for the very first time when user click on settings button, the first item is selected. and after then when user select other item, i have saved the i value so that next time when user click settings button, i can show user his/her previously selected item is selected.
I come across and solve this question today.
public class ItemChooceActivity extends Activity implements OnItemClickListener {
private int chosenOne = -1;
class Madapter extends BaseAdapter {
.....
.....
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
if (chosenOne != position) {
set the view in A style
} else {
set the view in B style
}
return convertView;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
,,,,
chosenOne = position;
adapter.notifyDataSetChanged();
,,,
}
}

How to show another List View 'B' after clicking List View 'A'

I'd like to show another List View 'B' after clicking a item of List View 'A'. I use onListItemClick event in Android 1.6 project.
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this,
"You have selected " + lv_arr[position],
Toast.LENGTH_SHORT).show();
}
how to code it?
If you want to stay on the same Activity and layout you could use a ViewSwitcher, which is designed for flipping between two views.
However I would strongly suggest that the click triggers a new local Activity via an Intent. This will have a new Layout containing your second ListView. This is because users will expect that having clicked and had the display significantly change, that pressing the back button will take them back to the original location in the app. As a general rule, any user action that changes the conceptual location in the application should be accompanied by an Activity change.
I could see the List View by adding
<activity android:name=".WhiteListView"/>
in AndroidMainfest.xml.
How about try ExpandableListView. When you click on the groupview it expands to show childviews. It has a nice BaseExpandableListAdapter.
For example I call a new activity using Intents, with packed values added this way...
#Override
public void onListItemClick( ListView parent, View v, int position, long id) {
Intent lancon = new Intent(this, viewContact.class);
//lancon.putExtra("id", id);
//or
c.moveToPosition(position);
id = c.getInt(0);
c.close();
lancon.putExtra("id", id);
this.startActivity(lancon);
finish();
}
Then in the other class onCreate method I call:
this._id = this.getIntent().getLongExtra("id", 0);

Categories

Resources