ListView with clickable/editable widget - android

Is it possible to use a OnItemClickListener on a ListView when the Items layout has a clickable/editable widget (RadioButton,EditText, or CheckBox)?

You might want to take a look at this issue. Having a focusable item in a row of a ListView causes the OnItemClickListener NOT to be invoked. However, that does not mean you cannot have focusable/clickable items in a row, there are some workarounds like this one.
Also, you can take a look at the Call Logs screen. It has a ListView with clickable item(the call icon on the right).
See Source code here

Quoting comment #31 in the link mentioned by Samuh (which solved the problem for me):
In fact you can add it to the layout XML (if inflated by one): android:descendantFocusability="blocksDescendants".
Adding here JIC that webpage is down in the future.

If any row item of list contains focusable or clickable view then OnItemClickListener won't work.
row item must be having param like android:descendantFocusability="blocksDescendants"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// your other widgets here
</LinearLayout>

Tried many complex solutions, but this was the simplest one that worked:
Just use android:focusable="false" as in:
<CheckBox
android:id="#+id/fav_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />

Two best solution
Add android:descendantFocusability="beforeDescendants" to listView
in xml OR
Set given two attributes to false
like
android:focusable="false"
android:focusableInTouchMode="false"
Then it will handle the listView row item child(Button,EditText etc) events instead of listView.setOnItemClick .

I fixed my problem different , in my item I have more than one LinearLayout
so if you give id to your linearayout and setOnclickListener in adapter class it will work, only original effect of touching will dissapear.
but this link Making a LinearLayout act like an Button is usefull to make linearlaout act like button on click
item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp">
<TextView
android:id="#+id/txt_item_followers_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:gravity="center|start"
android:paddingLeft="15dp"
android:text="Ali"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imageView"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/txt_item_followers_name"
android:layout_marginLeft="10dp"
android:src="#drawable/puan_icon" />
<TextView
android:id="#+id/txt_item_followers_mark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_toEndOf="#+id/imageView"
android:background="#color/red_400"
android:paddingLeft="10dp"
android:text="25.5"
android:textAppearance="?android:attr/textAppearanceSmall" />
<LinearLayout
android:id="#+id/linear_one"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/txt_item_followers_name"
android:background="#color/red_400"
android:orientation="vertical">
<ImageView
android:id="#+id/btn_item_followers_2b_follow"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_marginLeft="10dp"
android:src="#drawable/follow_buton" />
</LinearLayout>
</RelativeLayout>
inside getView method
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.deneme, null);
final Followers2 myObj = myList.get(position);
LinearLayout linear_one = (LinearLayout) view.findViewById(R.id.linear_one); // HERE WE DOMUNÄ°CATE IT
linear_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(parentActivity, "One Two", Toast.LENGTH_SHORT).show();
}
});
TextView name = (TextView) view.findViewById(R.id.txt_item_followers_name);
TextView mark = (TextView) view.findViewById(R.id.txt_item_followers_mark);
final ImageView btn_follow = (ImageView) view.findViewById(R.id.btn_item_followers_2b_follow);
name.setText(myObj.getName());
mark.setText(myObj.getScore());
/* if (myObj.isFollow() == true) {
btn_follow.setImageResource(R.drawable.following_buton);
} else {
btn_follow.setImageResource(R.drawable.follow_buton);
}
btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Followers2 myObj = myList.get(position);
if (myObj.isFollow() == true) {
btn_follow.setImageResource(R.drawable.following_buton);
} else {
btn_follow.setImageResource(R.drawable.follow_buton);
}
}
});*/
return view;
}

Related

ListView items aren't clickable when I show a LinearLayout as sibling

I'm having trouble with a ListView.
Basically, i have this hidden ListView to be shown on a TextView click.
This works ok.
When I click on a Item of the ListView, i would like to show another Layout(containing a TextView & a FloatingButton).
The problem is that when I show the LinearLayout, I can't click on the ListItem anymore. Any suggestions?
Here's some code:
Layout.xml
<ListView
android:id="#+id/meal_insertion_meals_portions_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/meal_insertion_location"
android:layout_above="#id/meal_insertion_add_container"/>
<LinearLayout
android:id="#id/meal_insertion_add_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="8dp">
<android.support.design.widget.FloatingActionButton
android:id="#+id/meal_insertion_add_meal_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#drawable/ic_add"
android:tint="#android:color/white"
app:backgroundTint="#color/colorPrimary"/>
<TextView
android:id="#+id/meal_insertion_add_meal_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:gravity="center_vertical|center_horizontal"
android:text="#string/diary.meal.insertion.aliment.add"
android:textColor="#color/colorPrimary"/>
</LinearLayout>
Fragment.java
mealSelector.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectorList.getVisibility() == View.VISIBLE) {
selectorList.setVisibility(View.GONE);
mealLocation.setVisibility(View.VISIBLE);
} else {
selectorList.setVisibility(View.VISIBLE);
mealLocation.setVisibility(View.GONE);
}
}
});
selectorList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView t1 = (TextView) view.findViewById(android.R.id.text1);
mealSelector.setText(t1.getText());
selectorList.setVisibility(View.GONE);
mealLocation.setVisibility(View.VISIBLE);
addLayoutContainer.setVisibility(View.VISIBLE);
}
}
);
THIS IS NOT THE RIGHT SOLUTION - Just a workaround:
I just hide the ContainerLayout again when I show the ListView.
This let me clicks on Items again.
AGAIN: Still looking for a better solution.
Try below solutions,
change listview, android:layout_height="wrap_content" to android:layout_height="match_parent", in addition try with removing android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false" from Floating button.

Android development : Listview with android:onclick attribute on item

I'm beginner in android development and i a have question about Listview and android:onclick attribute.
I try to use attribute android:onclick ="myMethod" on each element of my listview instead of define OnItemClickListener/onItemClick (too much verbose for me)
MyMethod is executed but how can i get clicked element (current context) ?
Thanks in advance
As a beginner, setting an OnItemClickListener might seem a bit scary, but it's really not a big deal at all (and a core concept you should be learning anyway!).
So if you have a simple layout with a ListView in it like this...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/containerView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/myListview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
You can set up an OnItemClickListener with just this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_listview_layout);
listView = (ListView)findViewById(R.id.myListview);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Every time an item is clicked, you can handle it right here.
}
});
}
So every time an item in your list is clicked, the onItemClick method is fired, and you can figure out which item was clicked by using the int position argument that comes in.
If i am right your question is about implementing on click listener on each listrow item instead of list row.
If that is correct this is how you should implement:
1.In your adapter of getView() method you might be inflating a layout for list row like below:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_row_layout, parent, false);
return convertView;
}
In the above code list_row_layout is the xml file i'm inflating.
Go to that layout and add the following line android:descendantFocusability="blocksDescendants" to the root level of the xml layout like below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_margin="4dp"
android:descendantFocusability="blocksDescendants"<!--This is the line i'm talking about-->
android:background="#drawable/rounded_border_layout"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="40dp"
android:layout_marginRight="10dp"
android:id="#+id/review_main_user_image_layout"
android:layout_marginLeft="10dp"
android:layout_height="54dp">
<ImageView
android:layout_width="40dp"
android:id="#+id/review_main_user_image"
android:background="#drawable/reviews_x_trail_user_image_border"
android:layout_height="40dp"
android:src="#drawable/ic_help_user" />
<TextView
android:typeface="monospace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Me"
android:textSize="10sp"
android:layout_gravity="center"
android:singleLine="true"
android:id="#+id/review_main_user_name"
android:layout_below="#+id/review_main_user_image" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/review_main_user_image_layout"
android:layout_toEndOf="#+id/review_main_user_image_layout">
<TextView
android:layout_marginLeft="8dp"
android:layout_width="wrap_content"
android:textColor="#color/black"
android:layout_height="wrap_content"
android:singleLine="true"
android:id="#+id/review_main_title"
android:text="Good Product For The Price"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:orientation="horizontal">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/review_main_rating"
android:progressDrawable="#drawable/apptheme_ratingbar_small_holo_light"
android:numStars="5"
style="?android:attr/ratingBarStyleSmall" />
<TextView
android:layout_marginLeft="8dp"
android:text="12-Jun-1993"
android:id="#+id/review_main_date"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
That't it now in your adapter getView method you can implement on click listener for each widget you have in that layout.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReviewsXTrailViewHolder reviewsXTrailViewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_row_review_main, parent, false);
TextView title = (TextView)convertView.findViewById(R.id.review_main_user_image);
//title.setOnclickListener()
return convertView;
}
In that above code i have added on click listener for textview.I hope it will work
Comment below if that doesn't work

Android ListView not detecting selection

I'm stumped. This one IS simple and I'm missing something simple but I'm just not getting anywhere.
I have a ListView that contains pretty simple items - TextView's that contain text of the form "N. name", where N is the position in the list and name is the name of the associated objects. I've created a ListAdapter that presents that information into the ListView.
The presentation stuff seems to work fine. It's the part where when I tap on a row that's not working. I just don't get a notification. If I set a onClickListener on the item (when it's generated in the Adapter) I do get a notification, but it's convoluted to make that work the way I'd like it to. I've tried a bunch of stuff - changing descendent focusability, enabling, disabling, setting itemsCanFocus to false, ... - but no luck on any of them.
I've included relevant code for configuring the view and the elements in the ListView.
In particular, what I'm trying to do is get that OnItemClickLister.onItemClick() to get invoked when I tap on a row. Any thoughts on what I'm doing wrong?
Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = FZMModel.getInstance(this);
setContentView(R.layout.activity_deploy);
TextView viewTitle = (TextView) findViewById(R.id.deploy_header);
if (model.getProfiles().size() == 0) {
viewTitle.setText(R.string.deploy_header_create);
} else {
viewTitle.setText(R.string.deploy_header_choose);
}
profileListView = (ListView) findViewById(R.id.profileListView);
profileListAdapter = new ProfileListAdapter(this, model);
profileListView.setAdapter(profileListAdapter);
profileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Log.d(TAG, String.format("Item %d selected (with id=0x%x)", position, id));
}
});
}
Adapter:
... relevant code from getView():
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Profile profile = model.getProfileAtIndex(position);
final int rowNum = position;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.profile_list_layout, parent, false);
}
TextView profileIndexView;
TextView profileNameView;
profileIndexView = (TextView) convertView.findViewById(R.id.profileIndexLabel);
profileNameView = (TextView) convertView.findViewById(R.id.profileNameLabel);
profileIndexView.setText(String.format("%d.", position));
profileNameView.setText(profile.getName());
// convertView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(context, String.format("Did select row #%d (index=%d)",rowNum, profile.getPosition()), Toast.LENGTH_SHORT).show();
// }
// });
return convertView;
}
activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nsn.flexizonemobile.FZMConcreteActionDeploy"
tools:ignore="MergeRootFrame" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/deploy_header_choose"
android:id="#+id/deploy_header"
android:layout_margin="10dp"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/profileListView"
android:layout_gravity="left|top"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:choiceMode="none"
android:layout_below="#+id/deploy_header"
android:divider="#android:color/darker_gray"
android:dividerHeight="2dp"
android:clickable="true"
android:descendantFocusability="beforeDescendants" />
</RelativeLayout>
profile_list_layout layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="#dimen/profile_index_width"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="A. "
android:id="#+id/profileIndexLabel"
android:gravity="center_vertical|right"
android:layout_centerVertical="true"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textSize="24sp"
android:textIsSelectable="true"
android:layout_alignParentStart="false"
android:layout_alignParentTop="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Profile Name"
android:id="#+id/profileNameLabel"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:gravity="center_vertical"
android:layout_toRightOf="#+id/profileIndexLabel"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"
android:textSize="24sp"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
</RelativeLayout>
in the textview of your inflator layout just add:
android:focusable="false"
android:focusableInTouchMode="false"
and in parent layout of your inflator i.e in relative layout of inflator add:
android:descendantFocusability="blocksDescendants"
remove :
android:descendantFocusability="beforeDescendants"
from your listview. and set height of your listview to match_parent will solve your issue.
remove following attributes from your ListView:
android:choiceMode="none"
android:clickable="true"
android:descendantFocusability="beforeDescendants"
also
android:layout_width="wrap_content"
android:layout_height="wrap_content"
makes no sense in this context (especially height)

ListView Delete Icon

I am trying to fire a event when a user click the delete icon in the list , But I could not able to do it.I am using a simple cursor adapter with setviewbinder to display items in the list.In the setviewBinder method I set the textview layout clicklistener to be null that's why, view is not clicked when a user click in the textview.When a user is swipe in the list immediately delete icon is appeared.I need to fire a click event in the deleteIcon.Currently, when a user is clicked the delete icon, the whole view is clickable.I need to achieve when a user is clicked the delete icon, need to fired the event, only in the delete icon.
public boolean setViewValue(final View view, final Cursor data, int columnIndex) {
LinearLayout layoutTaskView=(LinearLayout)view.findViewById(R.id.layoutTaskView),
layoutTaskDelete = (LinearLayout) view.findViewById(R.id.LayoutDeleteTask);
boolean crossed = Boolean.valueOf(data.getString(columnIndex));
if(crossed){
icon.setImageState(new int[] { android.R.attr.state_checked }, true);
text1.setPaintFlags(text1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
text2.setPaintFlags(text2.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
layoutTaskView.setOnClickListener(null);
}
}
Layout Xml File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/layoutTaskView"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight="1"
android:padding="15dp" >
<TextView
android:id="#+id/taskTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/taskName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:paddingLeft="10dp"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/LayoutDeleteTask"
android:clickable="false">
<ImageView
android:id="#android:id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:padding="15dp"
android:src="#drawable/checkmark" />
</LinearLayout>
</LinearLayout>
ListView xml
<com.myexample.CrossView
android:id="#+id/crossview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</com.myexample.CrossView>
Adapter Code
String[] from = new String []
{
DatabaseHelper.COLUMN_CATEGORY,DatabaseHelper.COLUMN_TASKNAME,
DatabaseHelper.COLUMN_CROSSED};
int[] to = new int[] {R.id.taskTime,R.id.taskName, android.R.id.content};
adapter = new SimpleCursorAdapter(context, R.layout.layout_list_item, data, from, to, 0);
adapter.setViewBinder(new CrossBinder());
lv.setAdapter(adapter);
public void onItemClick(AdapterView<?> parent, View v, final int position, final long id) {
ImageView icon = (ImageView)v.findViewById(android.R.id.icon);
icon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId() == android.R.id.icon){
}
}
}
You need to use android:descendantFocusability = "afterDescendants" parameter to root layout of list item. In your case, the root LinearLayout.
For more information check this link.
EDIT : remove android:clickable="false" from your LinearLayout containing ImageView. Put android:clickable="true" in ImageView. Moreover, you can use ImageButton instead ImageView.
P.S. I have suggested to use android:descendantFocusability in main parent LinearLayout.
Create custom adapter like that answer Custom adapter for a list of items that have multiple child items?
This answer give tutorial link to create custom dapters for listview.

Android ListView with RadioButton in singleChoice mode and a custom row layout

I have a ListView, which is in single-choice mode. All I want is to display a RadioButton to the side, that when clicked highlights to say it is selected, and when a different one is clicked that one goes back to unselected and the new one becomes selected. Why is this so hard? This should not be this complicated. I've spent DAYS looking for an appropriate answer to this and I have found nothing, so I'm asking hopefully clearly and concisely.
My layout for the listview (R.layout.view_orders):
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:choiceMode="singleChoice"
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#drawable/list_divider"
android:dividerHeight="1px"
android:focusable="false"
android:focusableInTouchMode="false"
android:cacheColorHint="#00000000">
</ListView>
My custom row (R.layout.orders_row):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:app="http://schemas.android.com/apk/res/com.xxx.xxxxxx"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="6dip">
<com.xxx.xxxxxx.VerticalLabelView
app:text="SHORT"
app:textColor="#666"
app:textSize="14sp"
android:id="#+id/state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/state"
android:layout_centerVertical="true"
android:gravity="center"
android:textSize="40sp"
android:layout_margin="2dip"
android:minWidth="30dip"
android:textColor="#555" />
<RelativeLayout
android:layout_toRightOf="#id/quantity"
android:layout_centerVertical="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/instrument"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#333"
android:layout_marginLeft="2dip"
android:layout_marginRight="2dip"
/>
<TextView
android:id="#+id/deets"
android:layout_below="#id/instrument"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#888"
android:layout_marginLeft="2dip"
android:layout_marginRight="2dip"
/>
</RelativeLayout>
<RadioButton
android:id="#+id/selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
My onCreate() method:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_orders);
client = new Client(handler);
ola = new OrdersAdapter(this, R.layout.orders_row, Orders);
setListAdapter(ola);
final RelativeLayout loading = (RelativeLayout) findViewById(R.id.loading);
panel = (PositionsPanel) findViewById(R.id.panel);
Utility.showProgressBar(loading);
client.Connect("orders");
}
Now everything underlying works as expected, you click on a radiobutton, and through its tag, I can appropriately select that item from the list and manipulate it how I want. However, when the first radio button is clicked, the last one will be selected. Click that same radio button again, and it is now selected as well. Click it once more and nothing happens, both the last and the first are selected. Now I click any other one on the list, it gets selected like expected. Click any one of the selected radio buttons and nothing happens, the radio button remains selected.
I have tried using the following in onCreate():
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_orders);
client = new Client(handler);
ola = new OrdersAdapter(this, android.R.layout.simple_list_item_single_choice, Orders);
setListAdapter(ola);
final RelativeLayout loading = (RelativeLayout) findViewById(R.id.loading);
panel = (PositionsPanel) findViewById(R.id.panel);
Utility.showProgressBar(loading);
client.Connect("orders");
}
and that just shows no radio buttons at all. AWESOME.
Now maybe (read: most likely), I'm just dense and can't figure this out, but I've seen this question asked a lot with no real answer. Lots of references to other tutorials or the Commonsware guy's book. However, the comments are old now and his repository has changed so much, that those are no longer correct answers.
So, does anyone have any idea how to get the expected functionality out of this? Or failing that, just pass me along with the Gmail app's source code. :)
Do bear in mind that in the ListView row items are RECYCLED. This is likely to explain why actions on one row are affecting another. Dig around in Mark's book and you'll find coverage of this.
If you're using an adapter with the list, you can use getView() on an adapter to add a click handler to each row as it's created/recycled, and make sure the state is managed correctly as the row items are created and recycled.
My approach is to store the state in my own data structure, and then use getView() to mirror that in the UI as the user scrolls up and down the ListView. There may be a better solution, but that works for me.
Simple solution:
Add this line in the RadioButton layout of your xml file:
<RadioButton
...
android:onClick="onClickRadioButton"
...
/>
Then in the activity class that uses the ListView, add the following:
private RadioButton listRadioButton = null;
int listIndex = -1;
public void onClickRadioButton(View v) {
View vMain = ((View) v.getParent());
// getParent() must be added 'n' times,
// where 'n' is the number of RadioButtons' nested parents
// in your case is one.
// uncheck previous checked button.
if (listRadioButton != null) listRadioButton.setChecked(false);
// assign to the variable the new one
listRadioButton = (RadioButton) v;
// find if the new one is checked or not, and set "listIndex"
if (listRadioButton.isChecked()) {
listIndex = ((ViewGroup) vMain.getParent()).indexOfChild(vMain);
} else {
listRadioButton = null;
listIndex = -1;
}
}
With this simple code only one RadioButton is checked.
If you touch the one that is already checked, then it returns to the unchecked mode.
"listIndex" is tracking the checked item, -1 if none.
If you want to keep always one checked, then code in onClickRadioButton should be:
public void onClickRadioButton(View v) {
View vMain = ((View) v.getParent());
int newIndex = ((ViewGroup) vMain.getParent()).indexOfChild(vMain);
if (listIndex == newIndex) return;
if (listRadioButton != null) {
listRadioButton.setChecked(false);
}
listRadioButton = (RadioButton) v;
listIndex = newIndex;
}
My Name Is Gourab Singha. I solved This Issue. I have Written This Code to solve it. I hope this helps you all. Thanks. I require 3 hours for this.
public void add_option_to_list(View v){
LinearLayout ll = (LinearLayout)v.getParent();
LinearLayout ll_helper = null;
LinearLayout ll2 = (LinearLayout)ll.getParent();
LinearLayout ll3 = (LinearLayout)ll2.getParent();
ListView ll4 = (ListView)ll3.getParent();
//RadioButton rb1= (RadioButton)ll.getChildAt(1);
Toast.makeText(getApplicationContext(), ", "+ll4.getChildCount(), Toast.LENGTH_LONG).show();
//ll.findViewById(R.id.radio_option_button)
for(int k=0;k<ll4.getChildCount();k++){
ll3 = (LinearLayout)ll4.getChildAt(k);
ll2 = (LinearLayout)ll3.getChildAt(0);
ll_helper = (LinearLayout)ll2.getChildAt(0);
RadioButton rb1 = (RadioButton)ll_helper.getChildAt(1);
if(rb1.isChecked())
rb1.setChecked(false);
}
RadioButton rb1 = (RadioButton)ll.getChildAt(1);
rb1.setChecked(true);
//Toast.makeText(getApplicationContext(), ""+((TextView)ll.getChildAt(4)).getText().toString(), Toast.LENGTH_LONG).show();
}
The XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Category Name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="gone" />
<RadioButton
android:id="#+id/radio_option_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="add_option_to_list"
android:text="" />
<TextView
android:id="#+id/option_name"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginLeft="3dp"
android:layout_weight="5.35"
android:text="Category Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/option_price"
android:layout_width="76dp"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="right"
android:text="$0.00"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/option_unit_price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:gravity="right"
android:text="$0.00"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="gone" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I've just had a similar problem. It seemed that it was related to views recycling. But I added Log's everywhere and noticed that the recycling handling was fine.
The problem was RadioButtons handling. I was using:
if(answer == DBAdapter.YES){
rbYes.setChecked(true);
rbNo.setChecked(false);
}
else if(answer == DBAdapter.NO){
rbYes.setChecked(false);
rbNo.setChecked(true);
}
else{
rbYes.setChecked(false);
rbNo.setChecked(false);
}
and the correct way of doing it is:
if(answer == DBAdapter.YES){
rbYes.setChecked(true);
}
else if(answer == DBAdapter.NO){
rbNo.setChecked(true);
}
else{
RadioGroup rg = (RadioGroup)(holder.answerView);
rg.clearCheck();
}
You can achieve much more simple, follow this. It was tried in MarshMallow
1)Have a CheckedTextView :
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceMedium">
ListChoiceIndicatorSingle will display RadioButton.
ListChoiceIndicatorMultiple will display CheckBox
Don't forgot to put choiceMode:Single in your ListView.
Inside the adapter
viewHolder.radioBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("called", "called");
if(position != mSelectedPosition && mSelectedRB != null){
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton)v;
}
});
viewHolder.radioBtn.setText(mList[position]);
if(mSelectedPosition != position){
viewHolder.radioBtn.setChecked(false);
}else{
viewHolder.radioBtn.setChecked(true);
if(mSelectedRB != null && viewHolder.radioBtn != mSelectedRB){
mSelectedRB = viewHolder.radioBtn;
}
}
add style to the radio button
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/tick" android:state_checked="true"/>
<item android:drawable="#drawable/untick" android:state_checked="false"/>
</selector>
and in the xml use the radio button style
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RadioButton
android:id="#+id/radioBtn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:button="#null"
android:checked="true"
android:drawablePadding="30dp"
android:drawableRight="#drawable/checkmark"
android:text="first" />
</RelativeLayout>
On your adapter:
public void setChecked(View v, int position) {
ViewGroup parent = ((ViewGroup) v.getParent()); // linear layout
for (int x = 0; x < parent.getChildCount() ; x++) {
View cv = parent.getChildAt(x);
((RadioButton)cv.findViewById(R.id.checkbox)).setChecked(false); // your checkbox/radiobtt id
}
RadioButton radio = (RadioButton)v.findViewById(R.id.checkbox);
radio.setChecked(true);
}
On your activity/fragment:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
((ModelNameAdapter)adapter).setChecked(view, position);
}
});

Categories

Resources