List item with CheckBox not clickable - android

I have a list item which contains a CheckBox, and I want to be able to click on the CheckBox and on the list item itself. Unfortunately, there seems to be some sort of conflict between the two, as I can only click on the item when I comment out the CheckBox. It seems like I recall there was a way to fix this, but I can't find it at the moment. Thanks
EDIT: This is with a ListFragment, so there's no need to call setOnItemClickListener.
OK, here's the XML for the list item. The problem is the CheckBox, but I figured might as well copy everything.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_item_survey"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/SimpleListItem">
<TextView
android:id="#+id/survey_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/ListItemTitle" />
<TextView
android:id="#+id/survey_date"
android:layout_below="#id/survey_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/ListItemSubtitle" />
<TextView
android:id="#+id/survey_completed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/survey_title"
android:textColor="#color/accent_1"
android:text="#string/survey_completed"
style="#style/ListItemSubtitle" />
<CheckBox
android:id="#+id/survey_did_not_attend"
android:layout_below="#id/survey_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/survey_did_not_attend"
android:focusable="false"
style="#style/ListItemSubtitle" />
</RelativeLayout>

You need to add this to your custom adapter xml file android:descendantFocusability="blocksDescendants"

insert this into the root element of the item row xml file
android:descendantFocusability="blocksDescendants"

As described here and here, this is either a known problem or works as designed. If you have any clickable or focusable items in a list item, the list item itself cannot be clickable. Romain Guy says "This is working as intended to support trackball/dpad navigation."

This did the work for me
<CheckBox
...
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false" />

I solved the problem this way. I implemented OnClickListener inside the Adapter and not in the Fragment/Activity and it works well. Now I can use ListView with checkboxes and can click on both. Here is my code:
public class MyFragment extends Fragment
{
...
private void setView()
{
ListView listView = (ListView) mRootView.findViewById(R.id.listview);
mItems = DatabaseManager.getManager().getItems();
// create adapter
if(listView.getAdapter()==null)
{
MyAdapter adapter = new MyAdapter(this, mItems);
try
{
listView.setAdapter(adapter);
}
catch(Exception e)
{
e.printStackTrace();
return;
}
}
else
{
try
{
((MyAdapter) listView.getAdapter()).refill(mItems);
BaseAdapter adapter = (BaseAdapter) listView.getAdapter();
listView.requestLayout();
adapter.notifyDataSetChanged();
}
catch(Exception e)
{
e.printStackTrace();
return;
}
}
// handle listview item click
listView.setClickable(true);
// listView.setOnItemClickListener(...); // this method does not work in our case, so we can handle that in adapter
}
...
}
public class MyAdapter extends BaseAdapter
{
...
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
{
LayoutInflater inflater = (LayoutInflater) mFragment.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listview_item, null);
}
...
// handle listview item click
// this method works pretty well also with checkboxes
view.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// do something here
// for communication with Fragment/Activity, you can use your own listener
}
});
return view;
}
...
}

Have you tried setting
android:focusable="false"
android:focusableInTouchMode="false"
?
It worked for me.

by using
android:descendantFocusability="blocksDescendants"
its working fine

ok.. Make a CheckBox instance Like
CheckBox check;
check = (CheckBox) myView.findViewById(R.id.check);
check.setOnClickListener(new CheckBoxSelect(position));
put above code in onItemClickListener or in Adapter you are using. now make a class like
below
private class CheckBoxSelect implements OnClickListener
{
int pos;
String str;
public CheckBoxSelect(int position)
{
pos = position;
}
public void onClick(View v)
{
}
}
perform any functionality in onClick .

Late, but nevertheless a solution for all those who still need it.
It is true that the built-in mechanism using:
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_multiple_choice, lst);
does not allow both, ie click on the checkbox AND click on the list item. Wherever one clicks, the checkbox catches the event.
However, if you create your own ArrayAdapter with getView like this, then it works fine:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item_ecu_fehler, null);
}
v.setFocusable(true);
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
" ->>"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
}
});
CheckBox selectedForClearingCB = (CheckBox) v
.findViewById(R.id.checkBox);
if (selectedForClearingCB != null) {
selectedForClearingCB.setTag(position); //so we know position in the list selectedForClearingCB.setChecked(true);
selectedForClearingCB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
" -> CB checked: "
+ Integer.toString((Integer) v
.getTag()));
}
}
});
}
}
return v;
}
}

Related

Remove item after click image from ListView (Fragment, BaseAdapter)

I have a problem. What I can remove item after click image on ListView? Every item on list has an icon to remove.
Part of fragment:
ListView listView;
.....
View view = inflater.inflate(R.layout.basic_list, container, false);
listView = (ListView) view.findViewById(R.id.list_view);
.....
listView.setAdapter(adapter);
Part of basic_list:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Part of ClassAdapter extends BaseAdapter:
public class ClassAdapter extends BaseAdapter {
...
public ClassAdapter(Context context) {
inflater = LayoutInflater.from(context);
cContext = context;
}
....
convertView = inflater.inflate(R.layout.list_adapter, null);
.....
holder.removeIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//????????????
}
Part of list_adapter.xml
<ImageView
android:id="#+id/icon"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/box_icon"/>
Below is a sample.
holder.removeIcon.setTag(position);//save index
holder.removeIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer position= (Integer) view.getTag(); //get index
dataList.remove(position); //remove the item from data source
notifyDataSetChanged(); //notify to refresh
}
});
Use these code
holder.removeIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ARRAYLIST.remove(position);///position of the getview method
notifyDataSetChanged(); //notify to refresh
}
}
You should remove the clicked item from your data list which should be located in your adapter class.
You probably didnt post the entire code of your adapter class, but your adapter probably a List of the data set that is shown in your listview based on positions?
In your adapters getView method you have a parameter "position", and you can use it to remove the item at that position from your data list and then just call notifyDataSetChanged so the ListView gets updated.

setVisibility(View.GONE) not removing space in listview item

I am making a question that could be like a duplicated question, but i have tried everything and nothing worked for me. I have created a listview witch every item has two views, one textview and one checkbox. Its like a multiselect listview. Every item has a level on its own: easy, normal, hard. When a level is chosen from a dropdown: All, Easy, Normal, Hard.. the list changes, just like a filter system.
But when i write listView.getChildAt(i).setVisibility(View.GONE); the content of the row is removed but the space occupied is not released.
Any help?
This is my code:
public class CreatePresentation extends Activity
{
DatabaseHelper db = new DatabaseHelper(this);
MyCustomAdapter dataAdapter = null;
List<Slider> list;
ListView listView;
String Text;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.create_presentation);
displayListView();
checkButtonClick();
}
private void displayListView()
{
list = new ArrayList<Slider>();
ArrayList<Slider> oldList = db.getAllSliders();
for (Slider anOldList : oldList) {
String s = anOldList.toString();
int in = anOldList.getId();
String lev = anOldList.getLevel();
Slider slider = new Slider(in, s, lev, false);
list.add(slider);
}
dataAdapter = new MyCustomAdapter(this, R.layout.list_check_box, list);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(dataAdapter);
}
private class MyCustomAdapter extends ArrayAdapter<Slider> {
private ArrayList<Slider> list;
public MyCustomAdapter(Context context, int textViewResourceId, List<Slider> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Slider>();
this.list.addAll(list);
}
private class ViewHolder {
TextView text;
CheckBox checkbox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final Slider slider = list.get(position);
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_check_box, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.sliderTitle);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
Spinner dropdown = (Spinner)findViewById(R.id.spinner);
String[] items = new String[]{"Tutto", "Facile", "Medio", "Difficile"};
ArrayAdapter<String> adapter = new ArrayAdapter<String (CreatePresentation.this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
Text = dropdown.getSelectedItem().toString();
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Slider slider = (Slider) cb.getTag();
slider.setSelected(cb.isChecked());
}
});
try {
if (list.get(position).getLevel().equals("Facile"))
convertView.setBackgroundColor(Color.parseColor("#477C3D"));
else if (list.get(position).getLevel().equals("Medio"))
convertView.setBackgroundColor(Color.parseColor("#936019"));
else if (list.get(position).getLevel().equals("Difficile"))
convertView.setBackgroundColor(Color.parseColor("#A02307"));
} catch (Throwable e) {
e.printStackTrace();
}
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, final int position, long id) {
Text = parentView.getItemAtPosition(position).toString();
try {
if (Text.equals("All")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
listView.getChildAt(i).setVisibility(View.VISIBLE);
}
}
};
runOnUiThread(run);
}
if (Text.equals("Easy")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Easy")) {
listView.getChildAt(i).setVisibility(View.VISIBLE);
}
else {
listView.getChildAt(i).setVisibility(View.GONE);
}
}
}
};
runOnUiThread(run);
}
if (Text.equals("Normal")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Normal"))
listView.getChildAt(i).setVisibility(View.VISIBLE);
else {
listView.getChildAt(i).setVisibility(View.GONE);
}
dataAdapter.notifyDataSetChanged();
}
}
};
runOnUiThread(run);
}
if (Text.equals("Hard")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Hard"))
listView.getChildAt(i).setVisibility(View.VISIBLE);
else
listView.getChildAt(i).setVisibility(View.GONE);
}
}
};
runOnUiThread(run);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Slider slider = (Slider) cb.getTag();
slider.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(slider.getQuestion());
holder.checkbox.setChecked(slider.isSelected());
holder.checkbox.setTag(slider);
return convertView;
}
}
the best way to do this is to remove the item from the list and call dataAdapter.notifyDataSetChanged()
As you want to remove your view but keep your item inside your List I suggest you to use a different method. When the user choose a value that will cause the item to be hide just set that value to your item and then call
dataAdapter.notifyDataSetChanged();
Doing this you have to modify the logic inside your getView(), I mean if you find an item that is eligible to get hide instead of return convertView inside the getView() method of your customAdapter just return an empty view, like this you item won't be shown but it will still be in your list;)
You can use a parent Layout for Yuor item to resolve the issue:
For example:
<LinearLayout ...>
<!-- Here Your item content starts -->
<LinearLayout android:id="#+id/content">
...
</LinearLayout>
<!-- Here Your content ends -->
</LinearLayout>
Java code:
listView.getChildAt(i).getChildAt(0).setVisibility(View.GONE);
just like a filter system. Why "like", why not make it actually filterable? There are two options. Easier one is overriding toString of your slider. Other one is creating custom filter, which wouldn't use object's toString method. However, I don't remember how exactly to do second one, only that it's possible.
Slider:
String toString(){
return this.type;
}
When spinner selection changes:
adapter.getFilter().filter(selectedDifficulty);
This will automatically display items you want to see.
You shouldnt change visibility of views generated by adapter - they change every time when you scroll listview. Instead you should change the behaviour of underlying adapter.
You can try this layout instead of the ListView since there's only 4 filters:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<include
android:id="#+id/filter_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
</LinearLayout>
When you want to hide one of the filters you can just do something like:
findViewById(R.id.filter_4).setVisibility(View.GONE);
EDIT:
For instance, if you want to add information to a TextView inside the first include you just have to call the View like this:
View filter1 = findViewById(R.id.filter_1);
TextView tv1 = (TextView) filter1.findViewById(R.id.<the_id_of_the_textview);
tv1.setText("StackOverflow filter");
To prevent add another layout in outside of your layout. You just hide the item's all child views, not item itself.
For example:
if(i == 1){ // assume we need hide the first item.
//item itself
ViewGroup parent = ((ViewGroup) holder.convertView);
for (int j = 0; j < parent.getChildCount(); j++) {
parent.getChildAt(j).setVisibility(View.GONE);
}
}
And i have test this code, works fine for me.

Check and Uncheck All CheckBoxes in ListView

I was surprised that I couldn't find an existing answer on Stack that I could use for this, so here I am.
I have a ListFragment with a list attached to a SimpleCursorAdapter comprised of the rows defined by the following row.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/story_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/story"
android:layout_width="wrap_content"
android:layout_height="24sp"
android:lines="1"
android:scrollHorizontally="true"
android:singleLine="true"
android:layout_alignBaseline="#+id/story_check_box"
android:layout_alignBottom="#+id/story_check_box"
android:layout_toRightOf="#+id/story_check_box" />
</RelativeLayout>
I connect the list with the adapter with the following code in my ListFragment:
adapter = new SimpleCursorAdapter(getActivity(), R.layout.row, null, new String[] { CProvider.Stories.TITLE }, new int[] { R.id.story }, 0);
setListAdapter(adapter);
I then try to use a CheckBox in my fragment to toggle all the list checkboxes as follows:
CheckBox selectAll = (CheckBox) rootView.findViewById(R.id.select_check_box);
selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final ListView listView = getListView();
for(int i=0; i < getListAdapter().getCount(); i++){
View view = getViewByPosition(i, listView);
CheckBox cb = (CheckBox)view.findViewById(R.id.story_check_box);
if (isChecked) {
cb.setChecked(true);
}
else {
cb.setChecked(false);
}
}
}
});
I got getViewByPositionfrom here: Get ListView children that are not in view, and that almost works, but a few of the checkboxes don't get checked (and there is a pattern to it, but I can't seem to figure it out). It also seems a bit kludgier than I would think is necessary.
I want the checkboxes on the left, so I don't want to use checkedtextviews. Maybe I need to extend CursorAdapter and override getView?
Thanks in advance.
Maybe I'm not correctly understanding your question but what I understood was that you wanted to check and uncheck all the checkboxes thanks to one "Select All checkbox".
Then, what I would do is to put the state of the "select all checkbox" as a variable of the class (as a boolean) which is overwritten by your selectAll.setOnCheckedChangeListener and say to the adapter "Hey, my state changed!" every time the checkbox changed its state.
Something like this:
class Dummy{
boolean isAllSelected = false;
Checkbox selectAll = (find or create your CheckBox)
selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) isAllSelected = true;
else isAllSelected = false;
listView.getAdapter().notifyDataSetChanged();
}
}
And then, you just have to override the getView() of this adapter (like you suggested) adding a "if (isAllSlected)" condition.
To me, it sounds the easiest to do but it's maybe not that good to call the notifyDataSetChanged() method every time the user clicks on a checkbox (it's not that efficient for so minor changes). Anyway, hope it helps (the code I wrote is maybe not with the correct syntax: I wrote it directly on the website form)!
Below is what I wound up doing. In addition to taking care of the "select all/ unselect all" functionality, it handles checking/unchecking a checkbox when the text of a list item is selected/unselected, and vice versa. I was concerned about getView being called frequently, but setItemChecked causes getView to be called no matter what, so there's a limit to how much calls to getView can be avoided. As ataulm mentioned in a comment, maybe a composite view would a solution with less fuss.
In onCreateView:
selectAllCheckBox = (CheckBox) rootView.findViewById(R.id.select_all_check_box);
selectAllCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final ListView listView = getListView();
for(int i=0; i < getListAdapter().getCount(); i++){
listView.setItemChecked(i, isChecked);
}
}
});
I also created a custom SimpleCursorAdapter with the following code, which also uses a simple ViewHolder class. In getView I check which items in the list are selected and check the checkboxes corresponding to those items. There's also code that sets a list item as selected or not if its corresponding checkbox has been clicked (i.e., checked or unchecked).
class AvailableCursorAdapter extends SimpleCursorAdapter {
AvailableCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
ViewHolder holder = (ViewHolder)row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
}
holder.storyCheckBox.setChecked(false);
holder.story.setTextColor(Color.LTGRAY);
long [] checkedIds = getListView().getCheckedItemIds();
if (checkedIds != null) {
for (int i = 0; i < checkedIds.length; i++) {
if (checkedIds[i] == getListAdapter().getItemId(position)) {
holder.storyCheckBox.setChecked(true);
holder.story.setTextColor(Color.WHITE);
break;
}
}
}
final boolean isChecked = holder.storyCheckBox.isChecked();
holder.storyCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getListView().setItemChecked(position, !isChecked);
}
});
return(row);
}
}
.
class ViewHolder {
CheckBox storyCheckBox;
TextView story = null;
ViewHolder(final View row) {
storyCheckBox = (CheckBox) row.findViewById(R.id.story_check_box);
story = (TextView) row.findViewById(R.id.story);
}
}
Finally, the following code causes getView to be called when a single ListItem is clicked, so that its corresponding checkbox gets selected or unselected, as appropriate:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
ViewHolder holder = (ViewHolder) v.getTag();
holder.storyCheckBox.setChecked(false);
holder.story.setTextColor(Color.LTGRAY);
long [] checkedIds = l.getCheckedItemIds();
if (checkedIds != null) {
for (int i = 0; i < checkedIds.length; i++) {
if (checkedIds[i] == getListAdapter().getItemId(position)) {
holder.storyCheckBox.setChecked(true);
holder.story.setTextColor(Color.WHITE);
break;
}
}
}
}

Custom Spinner not hiding the dropdown menu after selection

(Android API version 9)I created a spinner with a custom adapter and overrided getView() to inflate it with my xml file which has a text view. But now, my spinner is not closing the dropdown list after user selects an item. Is there anyway to close the spinner dropdown upon selecting an item?
Code
//Code in onCreate function
Spinner list = (Spinner) findViewById(R.id.spn_purchaseList);
listAdapter = new ItemListAdapter(this, new MyItemList());
list.setAdapter(listAdapter);
listAdapter.item_list.addItem(new MyItem("Test", "Test Item"));
listAdapter.notifyDataSetChanged();
//onCreate end
//the class below is inside "MainActivity extends Activity"
class ItemListAdapter extends BaseAdapter
{
Context context;
MyItemList item_list;
MyItem selectedItem;
ItemListAdapter(Context con,MyItemList k)
{
super();
this.context=con;
this.item_list=k;
selectedItem=null;
}
#Override
public int getCount() {
return item_list.getCount();
}
#Override
public MyItem getItem(int arg0) {
return this.item_list.getList().get(arg0);
}
#Override
public long getItemId(int arg0) {
return this.item_list.getPosition(this.item_list.getList().get(arg0));
}
#Override
public View getView(int position, View arg1, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View spinner_item = inflater.inflate(R.layout.spinner_layout, parent, false);
TextView tx = (TextView)spinner_item.findViewById(R.id.txt_spinner);
tx.setId((int) item_list.getPosition(item_list.getList().get(position)));
tx.setText(this.item_list.getList().get(position).name.toString());
tx.setBackgroundResource(R.drawable.spinner_item);
tx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedItem = item_list.getItem(v.getId());
list.setSelection(v.getId());
}
});
return spinner_item;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getView(position,convertView,parent);
}
}
Calling setVisibility(View.GONE) works to hide the dropdown but it seems to cause issues with the Spinner state, i.e. you will be unable to reopen the dropdown after it has been closed.
The preferred way is to get a handle to the Spinner and call its onDetachedFromWindow() from your onClick() listener.
#Override
public void onClick(View v) {
// code here to get selected item and do something with it
// hide the spinner dropdown
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
if (spinner != null) {
try {
Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
method.invoke(spinner);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Too late, but for my case I had a custom layout for spinner items. The clickable="true" or adding onClickListeners, onItemSelectedListeners didn't work because I was adding them to root layout.
When I changed my code as following, I added android:background="?attr/selectableItemBackground" to child of parent layout, and set OnItemSelectedListener() on Spinner, and it worked. Spinner dialog or dropdown hides when item is tapped.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground">
<!-- your custom spinner item view -->
</LinearLayout>
</LinearLayout>
just call spinner.dismissDropDown() method of spinner, inside on item click of spinner. Your problem will be solved.

Custom list View with edit text and check boxes

I'm new to programming and having problem with using getCheckedItemPositions() for check boxes and getting edit values from edit text in custom list view. Can anyone help me with an example to create custom list view which has above functionality. Thanks.
*this is custom listview xml code
<CheckBox android:id="#+id/checkBox" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:text="CheckBox"
android:onClick="clickHandler"
></CheckBox>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="TextView"
android:id="#+id/textView1"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true" android:layout_marginBottom="14dp"
android:layout_toLeftOf="#+id/checkBox">
*This is code for set up listview
lv1 = (ListView)dialog.findViewById(R.id.l1);
adapter2 = new SimpleCursorAdapter(
this,
R.layout.custom,
cursor2,
new String[] {"ItemName"},
new int[] {R.id.textView1});
lv1.setItemsCanFocus(false);
lv1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv1.setAdapter(adapter2);
*this what I tried to do when checked
public void onClick(View v) {
int len = lv1.getCount();
SparseBooleanArray checked = lv1.getCheckedItemPositions();
for (int i = 0 ; i < len; i++)
if (checked.get(i)) {
String item = mArrayList.get(i);
mItems.add(mArrayList.get(i));
System.out.println(item);
/* do whatever you want with the checked item */
}
But this is not working. And also I want to use edit text in this manner for getting values.when I checked and click the button app terminate.
The following code will solve your problem.
public class SimpleCursorAdapter extends ArrayAdapter {
private Context mcontext;
private View rowview;
LayoutInflater inflater;
public static ArrayList<Boolean > itemchecked=new ArrayList<Boolean>();
public SimpleCursorAdapter(Context context,ArrayList<String> mylist)
{
super(context,your layout id);
mcontext=context;
//this is the important step
for (int i = 0; i < this.getCount(); i++)
{
itemchecked.add(i,false); // initializes all items value with false
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
rowview=convertView;
if(convertView==null)
{
rowview = inflater.inflate(R.yourlayout, parent, false);
}
TextView textView_heading = (TextView) rowview.findViewById(R.id.textView1);
CheckBox checkbox_detail=(CheckBox) rowview.findViewById(R.id.checkBox1);
checkbox_detail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
if (cb.isChecked()) {
itemchecked.set(position, true);
// do some operations here
} else if (!cb.isChecked()) {
itemchecked.set(position, false);
// do some operations here
}
}
});
checkbox_detail.setChecked(itemchecked.get(position));
textView_heading.setText(userheading_list.get(position));
return rowview;
}
}
//now the custom list part finish
Now, to get all the information from list and also watch which checkbox is checked:
for(int i=0;i<yourlistadapterobject.getCount();i++)
{
View content_view=msg_adapter.getView(i,null , user_detail_list);
System.out.println("the list count"+user_detail_list.getCount());
if(MyContactAdapter.itemchecked.get(i))
{
System.out.println("is checked true");
TextView tv_heading= (TextView) content_view.findViewById(R.id.textView1);
String text=tv_heading.getText();
}
}
By doing this, you can get all the information against checkbox which is checked.

Categories

Resources