I created custom listview with two radiobutton in radiogroup.
My code getter and setter file
Item_radio.java
package com.example.customlistview_radio;
public class Item_radio
{
public boolean isSelected_radio1;
public boolean isSelected_radio2;
public Item_radio(boolean radio1_status,boolean radio2_status)
{
this.isSelected_radio1=radio1_status;
this.isSelected_radio2=radio2_status;
}
public boolean isSelected_radio1() {
return isSelected_radio1;
}
public void setSelected_radio1(boolean isSelected_radio1) {
this.isSelected_radio1 = isSelected_radio1;
}
public boolean isSelected_radio2() {
return isSelected_radio2;
}
public void setSelected_radio2(boolean isSelected_radio2) {
this.isSelected_radio2 = isSelected_radio2;
}
}
MyRadioAdapter.java
package com.example.customlistview_radio;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
public class MyRadioAdapter extends BaseAdapter
{
Context context;
List<Item_radio> radioList;
public MyRadioAdapter(Context context,List<Item_radio> radiolist)
{
this.context=context;
this.radioList=new ArrayList<Item_radio>();
this.radioList.addAll(radiolist);
}
#Override
public int getCount() {
return radioList.size();
}
#Override
public Object getItem(int position) {
return radioList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder
{
RadioButton radio_button1;
RadioButton radio_button2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
View view = convertView;
if(view==null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
view = inflater.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.radio_button1=(RadioButton)view.findViewById(R.id.my_radio_but1);
holder.radio_button2=(RadioButton)view.findViewById(R.id.my_radio_but2);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
if (position % 2 == 1)
{
view.setBackgroundColor(Color.CYAN);
}
else
{
view.setBackgroundColor(Color.WHITE);
}
final Item_radio radio = (Item_radio) getItem(position);
holder.radio_button1.setChecked(radio.isSelected_radio1());
holder.radio_button2.setChecked(radio.isSelected_radio2());
holder.radio_button1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e("button1","Clicked:button1");
RadioButton rb=(RadioButton)v;
radio.setSelected_radio1(rb.isChecked());
Log.e("button1","Clicked:button1:"+rb.isChecked());
}
});
holder.radio_button2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
RadioButton rb=(RadioButton)v;
Log.e("button2","Clicked:button2"+rb.isChecked());
radio.setSelected_radio2(rb.isChecked());
}
});
return view;
}
}
MainActivity.java
package com.example.customlistview_radio;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity
{
ListView mylist;
Button submit_but;
ArrayList<Item_radio> radio_list;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mylist=(ListView)findViewById(R.id.mylist_demo);
submit_but=(Button)findViewById(R.id.submit_but);
radio_list=new ArrayList<Item_radio>();
for(int i=0;i<20;i++)
{
radio_list.add(new Item_radio(false,false));
}
mylist.setAdapter(new MyRadioAdapter(MainActivity.this, radio_list));
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RadioGroup
android:id="#+id/my_radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RadioButton
android:id="#+id/my_radio_but1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="radio1" />
<RadioButton
android:id="#+id/my_radio_but2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="radio2" />
</RadioGroup>
</RelativeLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.customlistview_radio.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
/>
<ListView
android:id="#+id/mylist_demo"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:choiceMode="singleChoice"
tools:listitem="#layout/list_item"
android:layout_weight="0.3" >
</ListView>
<Button
android:id="#+id/submit_but"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="submit"
android:layout_weight="1.5"/>
</LinearLayout>
While selecting the radiobutton in list row some radiobutton is selected.
If i scroll the listview and select the radio button between last 5 or 6 items it will not selected.
Problem
That is suppose radio button1 is not selected then i choose radiobutton2 it gets selected afterwards radiobutton1 is selected.
My logCat
03-04 10:22:17.221: E/button2(4665): Clicked:button2true
03-04 10:22:20.201: E/button2(4665): Clicked:button2true
03-04 10:22:21.221: E/button2(4665): Clicked:button2true
03-04 10:22:22.101: E/button2(4665): Clicked:button2true
03-04 10:22:23.711: E/button2(4665): Clicked:button2true
03-04 10:22:24.671: E/button2(4665): Clicked:button2true
03-04 10:22:25.711: E/button2(4665): Clicked:button2true
03-04 10:22:40.770: E/button2(4665): Clicked:button2true
03-04 10:22:42.371: E/button2(4665): Clicked:button2false
03-04 10:22:52.271: E/button2(4665): Clicked:button2false
Please see my locat the first 8 rows working properly.
When i click radiobutton2 in 9 th row is not getting selected print checked status false but i select the button and also the checked appearance is not changed still in unselected mode.
Am i doing anything wrong?
Please help me to solve the problem.
Thank you...
One works sometime and same doesn't after, It's all because of you have used setChecked before rest of the codes. so what I can suggest to you is just remove these lines
holder.radio_button1.setChecked(radio.isSelected_radio1());
holder.radio_button2.setChecked(radio.isSelected_radio2());
UPDATE : If this harms your list, then do the following
Just reverse your logic here, After setting the radio_1 checked, set the radio_2 unchecked. Your code looks like this
holder.radio_button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("button1", "Clicked:button1");
RadioButton rb = (RadioButton) v;
radio.setSelected_radio1(rb.isChecked());
radio.setSelected_radio2(!rb.isSelected());
Log.e("button1", "Clicked:button1:" + rb.isChecked());
}
});
holder.radio_button2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
RadioButton rb=(RadioButton)v;
Log.e("button2","Clicked:button2"+rb.isChecked());
radio.setSelected_radio2(rb.isChecked());
radio.setSelected_radio1(!rb.isSelected());
}
});
UPDATE 2
Whatever currently happening is all because of your view is recycled, The final option you can use is, Remove this if(view==null) condition and matching else clause with it's code as well.
You need to change your code little bit.
Step 1:
Create HashMap in your adapter like this
HashMap<Integer,Integer> selectedItems = new HashMap<Integer, Integer>();
Step 2:
And inside of getView add the following
if ( selectedItems.get( position ) != null ) {
holder.radio_button1.setChecked(radio.isSelected_radio1()); selectedItems.get( position ) );
}
Step 3:
Inside of your radio button onlick add the following
selectedItems.put( position, your_value);
Note:
Here your_value is 0 or 1. If 1 means radio button selected 0 means not seleced.
Try this let me know if you face any issues.
I am adding this only for radio button 1. First try with this. If it is working then modify your radio button 2
Edit 1:
Why don't you try with Radiogroup like the following?????
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d("chk", "id" + checkedId);
}
});
Related
I want to change my Button text when i delete the items
i already checked it getText, when i getText it shows that the data
already changed but when i try to setText, it's not show to me
In this case what shold i do?
This is my f_productAdapter
package com.example.together.Adapter;
import android.content.Context;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.example.together.Activities.EditProfileActivity.TAG;
public class f_productAdapter extends BaseAdapter {
Button b;
LayoutInflater inflater = null;
private ArrayList<FuneralProdcutOrder> list;
public f_productAdapter(ArrayList<FuneralProdcutOrder> f_order) {
super();
list = f_order;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return list.get(position).hashCode();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_funeralorder, parent, false);
}
TextView tv_name = convertView.findViewById(R.id.productnm); //상품이름
TextView tv_price = convertView.findViewById(R.id.productpri); //상품 가격
ImageView tv_img = convertView.findViewById(R.id.pro_img);
Button tv_delete = convertView.findViewById(R.id.deleteBtn);
FuneralProdcutOrder getProlist = list.get(position);
tv_name.setText(getProlist.getName());
tv_price.setText(getProlist.getPrice());
Picasso.get().load(getProlist.getImg()).fit().into(tv_img);
LayoutInflater inflaters = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View Toplayout = inflaters.inflate(R.layout.activity_goodbyepet_reservation_result, null );
//
b = Toplayout.findViewById(R.id.f_orderBtn);
TextView test = Toplayout.findViewById(R.id.toolbar_title);
Log.e("test",test.getText()+"");
// Log.e("view context", parent.getContext()+"");
// Log.e("view position", position+"");
// Log.e("view count", list.size()+"");
// Log.e("view",b.getText()+"");
// b.setText("테스트");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("view alert" ,"확실히 버튼 객체를 찾았습니다 눌림");
}
});
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
return convertView;
}
}
This is my reservationResultActivity
package com.example.together.Activities.GoodbyePet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import com.example.together.Adapter.f_productAdapter;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class GoodbyepetReservationResultActivity extends AppCompatActivity {
// private TextView tvParent, tvChild;
Toolbar myToolbar;
ListView funeralview;
Button Btn;
private ArrayList<FuneralProdcutOrder> f_order = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goodbyepet_reservation_result);
int total_price = 0;
//리스트뷰선언
funeralview = findViewById(R.id.funeral_order);
//예약 버튼
Btn = findViewById(R.id.f_orderBtn);
//툴바 선언
myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
//액션바 왼쪽에 버튼
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_btn_back);
getSupportActionBar().setDisplayShowTitleEnabled(false);
for (int i = 0; i < MyCategoriesExpandableListAdapter.parentItems.size(); i++ ) {
for (int j = 0; j < MyCategoriesExpandableListAdapter.childItems.get(i).size(); j++ ){
String isChildChecked = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.IS_CHECKED);
if (isChildChecked.equalsIgnoreCase(ConstantManager.CHECK_BOX_CHECKED_TRUE)) {
// tvParent.setText(tvParent.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME));
// tvChild.setText(tvChild.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE));
String name = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME);
String price = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE);
String img = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_IMAGE);
f_order.add(new FuneralProdcutOrder(name,price,img));
total_price = total_price + Integer.parseInt(price);
}
}
}
f_productAdapter orAdapter = new f_productAdapter(f_order);
// orAdapter.setHasStableId(true);
Log.e("view activiey", f_order.size()+"안녕");
funeralview.setAdapter(orAdapter);
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//액션바 등록
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.alldelete_manu, menu) ;
return true ;
}
//액션바 클릭 이벤트
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// ((TextView)findViewById(R.id.textView)).setText("SEARCH") ;
return true;
case R.id.settings:
// ((TextView)findViewById(R.id.textView)).setText("ACCOUNT") ;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
What i want to do
when i delete the button directly change buttons text also change
but setText() is not working
how to change that?
Click delete button
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
What i want to change the button text
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
This is my XML That include button what i want to change the text
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".Activities.GoodbyePet.GoodbyepetReservationResultActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/mdtp_white"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="예약 상세서"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
/>
</android.support.v7.widget.Toolbar>
<ListView
android:id="#+id/funeral_order"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:drawSelectorOnTop="false">
</ListView>
<Button
android:id="#+id/f_orderBtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.8"
android:layout_margin="10dp"
android:text="바뀌어주세요"
android:background="#drawable/button_radius"
android:textSize="18dp"/>
</LinearLayout>
Create an interface class like this;
You can set many kind of information as a parameter about your deleted item and send it to your activity.
public interface ItemSelectedListener{
void onItemSelected(boolean isDeleted);
}
In your adapter initialize your interface;
private List<ItemSelectedListener> mItemSelectedSubscribers = new ArrayList<ItemSelectedListener>();
Add this method in your adapter ;
public void subscribeItemSelection(ItemSelectedListener listener) {
mItemSelectedSubscribers .add(listener);
}
Set this loop in your click events;
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (ItemSelectedListener listener : mItemSelectedSubscribers ) {
listener.onItemSelected(true);
}
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
In your activity, implement your interface and you will set a implemented methods. this methods look like this;
boolean isDeleted;
#Override
public void onItemSelected(boolean isDeleted) {
this.isDeleted = isDeleted;
}
You know now item is deleted or not. When a button deleted you can change text by using your method.
if(isDeleted){
btn.setText(changeText)
}
Hope this help!
I have gone through a lot of links here, but yet i was not able to get my stuff working. Can you please help me fetch data from my custom list.
Details are as under :- My custom list view
<?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" >
<RadioGroup
android:id="#+id/radioGroup_option"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"/>
<RadioButton
android:id="#+id/rb_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="#+id/rb_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
</LinearLayout>
I am populating a List through the UI the code for that is :-
package com.example.customadapter;
import java.lang.reflect.Array;
import java.util.Arrays;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CustomAdapter extends ActionBarActivity {
AddDataToArray mydata;
EditText qstno,qstn,opt1,opt2;
Button btn_save,btn_display;
int questio_no;
String question,option1,option2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_adapter);
mydata=AddDataToArray.getInstance();
qstno=(EditText)findViewById(R.id.edt_qstn_no);
qstn=(EditText)findViewById(R.id.edt_add_qstn);
opt1=(EditText)findViewById(R.id.edt_opt1);
opt2=(EditText)findViewById(R.id.edt_opt2);
btn_save=(Button)findViewById(R.id.btn_save);
btn_display=(Button)findViewById(R.id.btn_display);
btn_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
questio_no=Integer.parseInt(qstno.getText().toString());
question=qstn.getText().toString();
option1=opt1.getText().toString();
option2=opt2.getText().toString();
System.out.println("Questio added in the UI --> "+ question);
String statusReceived=mydata.AddingQuestions(questio_no, question, option1, option2);
Toast.makeText(getApplicationContext(), statusReceived, Toast.LENGTH_LONG).show();
qstn.setText("");
opt1.setText("");
opt2.setText("");
}
});
btn_display.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i=0;i<mydata.myQstnList.size();i++)
{
System.out.println("Qustion no"+mydata.myQstnList.get(i).getQstno());
System.out.println("Question -->"+mydata.myQstnList.get(i).getQstn());
//System.out.println("The First Option added was:-" + mydata.myQstnList.get(i).getOpt1());
}
Intent myIntent = new Intent(CustomAdapter.this, Mediator.class);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.custom_adapter, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Finally i made an adapter from base adapter as follows:-
package com.example.customadapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Question> mQuestion;
Context context;
public MyAdapter(Context context,List<Question> mQuestion) {
super();
this.context=context;
this.mQuestion = mQuestion;
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mQuestion.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mQuestion.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
ViewHolder holder;
if (convertView == null){
view = mInflater.inflate(R.layout.customized_view, parent,false);
holder = new ViewHolder();
holder.rg=(RadioGroup)view.findViewById(R.id.radioGroup_option);
holder.tv_qstn=(TextView)view.findViewById(R.id.tv_id);
holder.rb_opt1=(RadioButton)view.findViewById(R.id.rb_1);
holder.rb_opt2=(RadioButton)view.findViewById(R.id.rb_2);
view.setTag(mQuestion);
}else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
Question qstnRef=mQuestion.get(position);
holder.tv_qstn.setText(qstnRef.getQstn());
holder.rb_opt1.setText(qstnRef.getOpt1());
holder.rb_opt2.setText(qstnRef.getOpt2());
holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
//List<Question> data =(List<Question>) group.getTag();
//Toast.makeText(context,(CharSequence) data.get(checkedId).getOpt2(),Toast.LENGTH_SHORT).show();
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
RadioButton r_btn=(RadioButton)group.getChildAt(i);
if (r_btn.getId() == checkedId){
System.out.println(r_btn.getText().toString());
}
}
}
});
return view;
}
private class ViewHolder {
public TextView tv_qstn;
public RadioButton rb_opt1,rb_opt2;
public RadioGroup rg;
}
}
But i am trying to get this data that i enter in the UI, but I am not able to get this to work, please provide me assistance !!!!
The code in the current format is giving me runtime error :-
05-09 06:01:06.669: E/AndroidRuntime(2420):
java.lang.ClassCastException: android.widget.TextView cannot be cast
to android.widget.RadioButton
05-09 06:01:06.669: E/AndroidRuntime(2420): at
com.example.customadapter.MyAdapter$1.onCheckedChanged(MyAdapter.java:83)
group.getChildCount() returns 3 as it has 3 child. but 1 child is of TextView that's why you were getting java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.RadioButton
To avoid it do type checking using instanceof before typecasting.
do like this:
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
if(group.getChildAt(i) instanceof RadioButton ) { // check if child is `RadioButton`
RadioButton r_btn = (RadioButton) group.getChildAt(i);
if (r_btn.getId() == checkedId) {
System.out.println(r_btn.getText().toString());
}
}
}
I'm getting an NPE on my code. I'm trying to get the value of the selected RadioButton. When I click the Button the Exception gets fired, don't know why, I could imagine that it takes the wrong view...
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class CategoryDialog extends DialogFragment{
Button btnDone;
RadioGroup rg;
RadioButton radioBtn;
String selectedCategory;
Communicator communicator;
public static interface Communicator{
public void onCategorySelected(String category);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
communicator = (Communicator) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_video_detail_category_dialog, container);
this.getDialog().setTitle(getString(R.string.z2_videodetail_category_dialog_title));
btnDone = (Button) view.findViewById(R.id.category_done_btn);
rg = (RadioGroup) view.findViewById(R.id.category_radioGroup);
btnDone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = rg.getCheckedRadioButtonId();
radioBtn = (RadioButton) v.findViewById(selectedId);
selectedCategory = radioBtn.getText().toString();
if(v.getId() == R.id.category_done_btn){
communicator.onCategorySelected(selectedCategory);
dismiss();
}
}
});
return view;
}
}
XML-FILE
<?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="wrap_content" >
<RadioGroup
android:id="#+id/category_radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
<RadioButton
android:id="#+id/category_radioGroup_radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/z2_videodetail_category_dialog_radioButton1" />
<RadioButton
android:id="#+id/category_radioGroup_radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/z2_videodetail_category_dialog_radioButton2" />
<RadioButton
android:id="#+id/category_radioGroup_radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/z2_videodetail_category_dialog_radioButton3" />
<RadioButton
android:id="#+id/category_radioGroup_radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/z2_videodetail_category_dialog_radioButton4" />
</RadioGroup>
<Button
android:id="#+id/category_done_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/category_radioGroup"
android:text="#string/z2_videodetail_category_dialog_done_btn" />
</RelativeLayout>
Thank you very much, highly appreciating your help! :)
You named your fragment View as view, but you also have the variable view inside of the onClick method referring to the button itself, so when you are finding the radio button by id, the program is looking into the wrong view. Is looking inside the button instead of looking into your fragment. Rename the variable view on the onClick method to avoid this confusion
And you have to declare the view object as final so it's available in the anonymous inner class!
final View view = inflater.inflate(R.layout.fragment_video_detail_category_dialog, container);
this.getDialog().setTitle(getString(R.string.z2_videodetail_category_dialog_title));
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.category_radioGroup);
#Override
public void onClick(View v) { //Change it from view to v or whatever you want
int selectedId = rg.getCheckedRadioButtonId();
radioBtn = (RadioButton) view.findViewById(selectedId);
selectedCategory = radioBtn.getText().toString();
if(v.getId() == R.id.category_done_btn){ //And update this value
communicator.onCategorySelected(selectedCategory);
dismiss();
}
}
Is there a callback/method I can use to tell is a Spinner is displayed?
And is there a callback/method I can use to tell when the Spinner is no longer displayed?
setOnItemSelectedListener/onItemSelected is called when an item from the list is selected - but is there any method/callback when the list is removed because the user touches outside the list?
You can get it by creating your custom spinner ,
after create your layout , you should use it in your layout ,
// com.talha.examples is package name
mySpinner.java
package com.talha.examples;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Spinner;
import android.widget.Toast;
public class mySpinner extends Spinner {
Context context;
public mySpinner(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
#Override
protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if(visibility == View.VISIBLE)
Toast.makeText(this.context, "VISIBLE NOW", 1000).show();
if(visibility == View.GONE)
Toast.makeText(this.context, "HAS GONE", 1000).show();
}
}
activity_main_spinner.xml
<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" >
<com.talha.examples.mySpinner
android:id="#+id/mySpinner"
android:layout_width="fill_parent"
android:layout_height="300dp"
android:background="#ffffaa" >
</com.talha.examples.mySpinner>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mySpinner"
android:text="Button" />
</RelativeLayout>
MainActivity .java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button button;
com.talha.examples.mySpinner mySpinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_spinner);
mySpinner = (com.talha.examples.mySpinner) findViewById(R.id.mySpinner);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mySpinner.getVisibility() == View.VISIBLE) {
mySpinner.setVisibility(View.GONE);
} else {
mySpinner.setVisibility(View.VISIBLE);
}
}
});
}
}
I wanted to be able to determine when the spinner menu was displayed, and dismissed as well. After a lot of searching, there wasn't a lot of good solutions. I was able to accomplish this by doing the following:
Created a custom spinner class, and override the following method:
#Override
public boolean performClick() {
this.isDropDownMenuShown = true; //Flag to indicate the spinner menu is shown
return super.performClick();
}
In my Activity, override the method onWindowFocusChanged(boolean hasFocus). If hasFocus == true && the flag in #1 is set to true, then the spinner has been dismissed (can be either by selection or tapping outside the spinner).
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (actionBarSpinner.isDropdownShown() && hasFocus) {
actionBarSpinner.setDropdownShown(false);
//Do you work here
}
}
Good luck!
I'm having problems using s.requestFocus() when s is a spinner. Is there a special treatment to get it to work when it's a spinner ?
Thanks
try this code..
spinner.setFocusable(true);
spinner.setFocusableInTouchMode(true);
I'm guessing you aren't literally just looking to "give focus" to the spinner. When you give focus to an EditText, the keyboard pops up, so you may be expecting the spinner selection to "open up" on focus - but it doesn't work that way (don't ask me why). Use s.performClick() to do this - it will act just as if the user clicked on the spinner control.
use this
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class dynamic_spinner_main extends Activity {
private Spinner m_myDynamicSpinner;
private EditText m_addItemText;
private ArrayAdapter<CharSequence> m_adapterForSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_spinner);
///////////////////////////////////////////////////////////////
//grab our UI elements so we can manipulate them (in the case of the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
////////////////////////////////////////////////////////////////
//create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
m_adapterForSpinner.add("gr");
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
startActivity(mIntent);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
addButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
clearButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
private void addNewSpinnerItem() {
CharSequence textHolder = "" + m_addItemText.getText();
m_adapterForSpinner.add(textHolder);
}
private void clearSpinnerItems() {
m_adapterForSpinner.clear();
m_adapterForSpinner.add("dummy item");
}
}
main_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_height="wrap_content"
android:layout_margin="4px"
android:id="#+id/newSpinnerItemText"
android:layout_width="fill_parent"></EditText>
<Button android:layout_height="wrap_content"
android:id="#+id/AddBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Add To Spinner"></Button>
<Button android:layout_height="wrap_content"
android:id="#+id/ClearBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Clear Spinner Items"></Button>
<Spinner android:layout_height="wrap_content"
android:id="#+id/dynamicSpinner"
android:layout_margin="4px"
android:layout_width="fill_parent"></Spinner>
</LinearLayout>
Spinner isn't focusable by default (source). So you have to make it focusable either in xml
<Spinner
android:id="#+id/spinner"
android:focusable="true"
android:layout_width="wrap_conten"
android:layout_height="wrap_content" />
or in code
findViewById(R.id.spinner).setFocusable(true);