ListView with MyAdapter that contains two TextViews and CheckBox - android

I have a problem syncing the list items isChecked state with the checkboxes that in the same raw. I am able to set the 'checked' state in list items but can't figure how to set the 'checked' state of the CheckBoxes. I thought mainListView.setItemChecked should do the work but it doesn't.
This is the code i'm using:
public class Reservation_Activity extends ListActivity {
int total=0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reservation);
total_tv = (TextView) findViewById(R.id.total_sum);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Save button", Toast.LENGTH_SHORT).show();
}
});
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
total=0;
total_tv.setText("Pick and Send");
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
// Prepare an ArrayList of todo items
ArrayList<name_price> listTODO = PrepareListFromXml();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
// Bind the data with the list
lv_arr = (name_price[]) listTODO.toArray(lv_arr);
mainListView.setAdapter(new MyAdapter(this,android.R.layout.simple_list_item_multiple_choice,lv_arr));
mainListView.setItemsCanFocus(false);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
name_price item = (name_price) mainListView.getItemAtPosition(position);
if(mainListView.isItemChecked(position))
{
mainListView.setItemChecked(position, false);
total = total - item._price;
} else {
mainListView.setItemChecked(position, true);
total += item._price;
}
total_tv.setText("Total: " + total);
}
});
}
private void ClearSelections() {
total=0;
// user has clicked clear button so uncheck all the items
int count = this.mainListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mainListView.setItemChecked(i, false);
}
}
private ArrayList<name_price> PrepareListFromXml() {
ArrayList<name_price> todoItems = new ArrayList<name_price>();
XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
int id=0;
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = todolistXml.getName();
if (strNode.equals("item")) {
todoItems.add(new name_price(id,todolistXml.getAttributeValue(null, "title"), Integer.parseInt(todolistXml.getAttributeValue(null, "price"))));
id++;
}
}
try {
eventType = todolistXml.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return todoItems;
}
public class MyAdapter extends ArrayAdapter<name_price> {
name_price[] items;
public MyAdapter(Context context, int textViewResourceId,
name_price[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_raw_resevation, parent, false);
TextView name,price;
CheckBox ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
ckbx.setChecked(mainListView.isItemChecked(position));
name = (TextView) row.findViewById(R.id.res_name);
name.setText(items[position]._name);
price = (TextView) row.findViewById(R.id.res_price);
price.setText(Integer.toString(items[position]._price));
return row;
}
public name_price getItem(int position) {
return items[position];
}
}
}
class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;
public name_price(int id, String name, int price)
{
this._id=id;
this._name = name;
this._price = price;
}
public name_price() {
// TODO Auto-generated constructor stub
}
}
I think I should change the checked state of the specific checkbox in mainListView.setOnItemClickListener according to this but I can't find a way to do it.
in addition, This is the raw layout and the list layout (of others to use):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<LinearLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<TextView
android:id="#+id/res_name"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:gravity="center|left"
android:singleLine="true"
android:text="lalalalalalalalalallaallllaaaa"
android:textColor="#ffffff" />
<TextView
android:id="#+id/res_price"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginRight="10dp"
android:gravity="center"
android:text="90"
android:textColor="#ffffff"
android:textSize="15dp" />
</LinearLayout>
<CheckBox android:text=""
android:id="#+id/UpdateCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
</LinearLayout>
List layout:
<!--?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" android:background="#81BEF7"
android:scrollbars="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout" android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:height="32dp" android:gravity="left|top" android:background="#2B60DE"
android:paddingTop="2dp" android:paddingBottom="2dp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout2" android:orientation="horizontal"
android:layout_height="wrap_content" android:gravity="left|center_vertical"
android:layout_width="wrap_content" android:layout_gravity="left|center_vertical">
<TextView android:id="#+id/total_sum" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:textStyle="bold"
android:textColor="#FFFFFF" android:text="#string/list_header"
android:textSize="15sp" android:gravity="center_vertical"
android:paddingLeft="5dp">
</TextView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout22" android:orientation="horizontal"
android:layout_height="wrap_content" android:gravity="right"
android:layout_width="fill_parent" android:layout_gravity="right|center_vertical">
<Button android:id="#+id/btnSave" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Send" android:textSize="15sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginBottom="2px" android:layout_marginTop="2px"
android:height="15dp" android:width="70dp">
</Button>
<Button android:id="#+id/btnClear" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Clear" android:textSize="15sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginBottom="2px" android:layout_marginTop="2px"
android:height="15dp" android:width="70dp">
</Button>
</LinearLayout>
</LinearLayout>
<TableLayout android:id="#+id/TableLayout01" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<ListView android:id="#android:id/list" android:layout_width="wrap_content"
android:textColor="#000000" android:layout_height="wrap_content">
</ListView>
</TableRow>
</TableLayout>
</LinearLayout>
Thanks!
Y

Good morning, I understand this should solve your problem:
public class Reservation_Activity extends ListActivity {
int total = 0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_raw_resevation);
total_tv = (TextView) findViewById(R.id.total_sum);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Save button", Toast.LENGTH_SHORT).show();
}
});
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
total = 0;
total_tv.setText("Pick and Send");
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
// Prepare an ArrayList of todo items
ArrayList<name_price> listTODO = PrepareListFromXml();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
// Bind the data with the list
lv_arr = (name_price[]) listTODO.toArray(lv_arr);
mainListView.setAdapter(new MyAdapter(this,
android.R.layout.simple_list_item_multiple_choice, lv_arr));
mainListView.setItemsCanFocus(false);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
name_price item = (name_price) mainListView
.getItemAtPosition(position);
if (mainListView.isItemChecked(position)) {
total = total - item._price;
} else {
total += item._price;
}
mainListView.setItemChecked(position,
mainListView.isItemChecked(position));
item.ckbx.setChecked(mainListView.isItemChecked(position));
total_tv.setText("Total: " + total);
}
});
}
private void ClearSelections() {
total = 0;
int count = this.mainListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mainListView.setItemChecked(i, false);
}
}
private ArrayList<name_price> PrepareListFromXml() {
ArrayList<name_price> todoItems = new ArrayList<name_price>();
XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
int id = 0;
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = todolistXml.getName();
if (strNode.equals("item")) {
todoItems.add(new name_price(id, todolistXml.getAttributeValue(null, "title"),Integer.parseInt(todolistXml.getAttributeValue(null,"price"))));
id++;
}
}
try {
eventType = todolistXml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return todoItems;
}
public class MyAdapter extends ArrayAdapter<name_price> {
name_price[] items;
View row;
CheckBox ckbx;
public MyAdapter(Context context, int textViewResourceId,name_price[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.reservation, parent, false);
TextView name, price;
ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
ckbx.setChecked(mainListView.isItemChecked(position));
ckbx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name_price item = (name_price) mainListView.getItemAtPosition(position);
if (ckbx.isChecked()) {
total = total - item._price;
} else {
total += item._price;
}
mainListView.setItemChecked(position,ckbx.isChecked());
total_tv.setText("Total: " + total);
}
});
items[position].setCkbx(ckbx);
name = (TextView) row.findViewById(R.id.res_name);
name.setText(items[position]._name);
price = (TextView) row.findViewById(R.id.res_price);
price.setText(Integer.toString(items[position]._price));
return row;
}
public name_price getItem(int position) {
return items[position];
}
}
}
and:
class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;
public name_price(int id, String name, int price) {
this._id = id;
this._name = name;
this._price = price;
}
public void setCkbx(CheckBox ckbx) {
this.ckbx = ckbx;
}
}

Related

RadioButton state and Button validation

I am facing two issues.
Radio buttons in radiogroup loosing state: when I click yes or no and scroll down the list view it looses the radiobutton value which is checked. I tried many ways to fix it but unable to achieve.
Submit button validation(Please refer image four): list of questions user should select either yes or no before clicking on submit button, if user click on submit button without selecting either yes or no it should them a toast message. all the questions should be selected with either yes or no. More specific each radiogroup should give me yes or no, not empty string.
Thanks in advance.
Custom Adapter
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.list_items, null);
TextView question = (TextView) view.findViewById(R.id.question);
final RadioButton yes = (RadioButton) view.findViewById(R.id.yes);
final RadioButton no = (RadioButton) view.findViewById(R.id.no);
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (yes.isChecked()) {
yes.setBackgroundColor(Color.GREEN);
no.setBackgroundColor(Color.BLACK);
}
if (no.isChecked()){
no.setBackgroundColor(Color.rgb(255,165,0));
yes.setBackgroundColor(Color.BLACK);
}
}
});
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "1");
}
});
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "2");
}
});
question.setText(questionsList[i]);
return view;
}
Main Activity
public class MainActivity extends AppCompatActivity {
ListView simpleList;
String[] questions;
Button submit,submit1;
FileOutputStream fstream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questions = getResources().getStringArray(R.array.questions);
simpleList = (ListView) findViewById(R.id.simpleListView);
View footerView = getLayoutInflater().inflate(R.layout.footer,null);
submit = (Button) footerView.findViewById(R.id.submit1);
simpleList.addFooterView(footerView);
View headerView = getLayoutInflater().inflate(R.layout.header, null);
simpleList.addHeaderView(headerView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
try {
fstream = openFileOutput("user_answer", Context.MODE_PRIVATE);
fstream.write(message.getBytes());
fstream.close();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
Intent inent = new Intent(v.getContext(), DetailsActivity.class);
startActivity(inent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
XML main layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/Black"
android:padding="10dp">
<RelativeLayout
android:id="#+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#drawable/round_relativelayout"
>
<ListView
android:id="#+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/Black"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
/>
</RelativeLayout>
List item XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#color/LightGrey">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="#dimen/activity_horizontal_margin"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout 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=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:background="#color/Black"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textColor="#color/White"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="#color/Black"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textColor="#color/White"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
Image oneImage twoImage threeImage four with submit button
Try the following:
1) MainActivity_.class:-----
public class MainActivity_ extends AppCompatActivity {
private ListView lv;
private CustomAdapter customAdapter;
private String[] questions;
private Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout8);
questions = new String[10];
for(int i = 0 ; i<10 ; i++){
questions[i] = "Q " + i;
}
lv = (ListView) findViewById(R.id.lv);
customAdapter = new CustomAdapter(getApplicationContext() , questions);
lv.setAdapter(customAdapter);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean found_unanswered = false;
if(customAdapter != null){
for(int i = 0 ; i<customAdapter.getSelectedAnswers().size() ; i++){
if(customAdapter.getSelectedAnswers().get(i).equals("3")){
found_unanswered = true;
break;
}
}
}
if(!found_unanswered){
Toast.makeText(getApplicationContext() , "All Answered" , Toast.LENGTH_LONG).show();
//Go to other activity
}
}
});
}
}
2) CustomAdapter.class:------
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("3");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return questionsList[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (convertView == null) {
if (inflter != null) {
view = inflter.inflate(R.layout.list_items, null);
}
}
TextView question = (TextView) view.findViewById(R.id.question);
question.setText(questionsList[i]);
// initialize/ restore UI Radio Button State
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
RadioButton rb_yes = (RadioButton) rg.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) rg.findViewById(R.id.no);
if(selectedAnswers.get(i).equals("1")){
rg.check(R.id.yes);
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
}else if(selectedAnswers.get(i).equals("2")){
rg.check(R.id.no);
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
}else{
// no answer.
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.GRAY);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb_yes = (RadioButton) group.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) group.findViewById(R.id.no);
switch (checkedId){
case R.id.yes:
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
selectedAnswers.set(i, "1");
break;
case R.id.no:
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
selectedAnswers.set(i, "2");
break;
}
}
});
return view;
}
public List<String> getSelectedAnswers(){
return selectedAnswers;
}
}
3) layout8.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"
android:weightSum="100">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="80"
android:id="#+id/lv">
</ListView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/lv"
android:layout_weight="20"
android:text="Submit"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/submit"/>
</LinearLayout>
4) list_items.xml:-----
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout 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=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
</LinearLayout>
Try this.
Use ViewHolder so it does not lose the data set
Custom Adapter class
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = inflter.inflate(R.layout.list_items, null);
viewHolder = new ViewHolder();
ViewHoldwe.question = (TextView) view.findViewById(R.id.question);
viewHolder.yes = (RadioButton) view.findViewById(R.id.yes);
viewHolder.no = (RadioButton) view.findViewById(R.id.no);
viewHolder.rg = (RadioGroup) view.findViewById(R.id.radio_group);
view.setTag(viewHolder)
}else{
viewHolder = (ViewHolder) view.getTag();
viewHolder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (viewHolder.yes.isChecked()) {
viewHolder.yes.setBackgroundColor(Color.GREEN);
viewHolder.no.setBackgroundColor(Color.BLACK);
}
if (viewHolder.no.isChecked()){
viewHolder.no.setBackgroundColor(Color.rgb(255,165,0));
viewHolder.yes.setBackgroundColor(Color.BLACK);
}
}
});
viewHolder.yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "1");
}
});
viewHolder.no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "2");
}
});
question.setText(questionsList[i]);
}
return view;
}
Make a private inner class
private class ViewHolder{
RadioButton yes;
TextView question;
RadioButton no ;
RadioGroup rg;
}

how to get radibutton Postion from listview On Button click in android

This is my screenshot:
This is my adapter class:
public class ListofAddressesAdapter extends ArrayAdapter<ListofAddressesDataModel> {
private Context context;
private int layoutResourceId;
HashMap<Integer, Integer> hashMap;
private List<ListofAddressesDataModel> data;
int selectedPosition = 0;
String name, phone, address;
String customeraddressid;
public ListofAddressesAdapter(Context context, int layoutResourceId,
List<ListofAddressesDataModel> data) {
super(context, R.layout.listofaddresses, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.name = (TextView) row.findViewById(R.id.tvsubservices);
holder.description = (TextView) row.findViewById(R.id.tvdesc);
holder.fulladd = (TextView) row.findViewById(R.id.tvfulladdr);
holder.r = (RadioButton) row.findViewById(R.id.radioButton);
holder.delet = (ImageView) row.findViewById(R.id.ivdelete);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ListofAddressesDataModel item = data.get(position);
holder.name.setText(item.getName());
holder.description.setText(item.getPhone());
holder.fulladd.setText(item.getFulladdress());
holder.r.setChecked(position == selectedPosition);
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView name;
TextView description;
TextView fulladd;
RadioButton r;
ImageView delet;
}
public Object getItemAtPosition(int position) {
// TODO Auto-generated method stub
return null;
}
}
This is my activity class:
public class testclass extends Activity implements View.OnClickListener{
List<ListofAddressesDataModel> lstDataModel;
ListView add;
JSONArray _jsonarray;
JSONObject jsonObject;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
add = (ListView) findViewById(R.id.add);
setContentView(R.layout.test);
add=(ListView)findViewById(R.id.add);
lstDataModel=new ArrayList<>();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
new manageaddresses().execute();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button)
{
}
}
class manageaddresses extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String response = JSONfunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/CustomerAddresses?CustomerID=4");
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ListofAddressesDataModel datamodel = new ListofAddressesDataModel();
jsonObject = _jsonarray.getJSONObject(i);
String customeraddressid = jsonObject.getString("CustomerAddressID");
datamodel.setCustaddid(customeraddressid);
String fullname = jsonObject.getString("FullName");
datamodel.setName(fullname);
String housenumber = jsonObject.getString("HouseNumber");
String phonenumber = jsonObject.getString("PhoneNumber");
datamodel.setPhone(phonenumber);
String area = jsonObject.getString("Area");
String landmark = jsonObject.getString("Landmark");
String city = jsonObject.getString("City");
String fulladdress = housenumber + "," + " " + area + "," + " " + landmark + "," + " " + city;
datamodel.setFulladdress(fulladdress);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListofAddressesAdapter adapter = new ListofAddressesAdapter(testclass.this, R.layout.listofaddresses, lstDataModel);
add.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
This is my item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="20dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:buttonTint="#999999"
android:text="New RadioButton" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingBottom="10dp">
<TextView
android:id="#+id/tvsubservices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/radioButton"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="TextView"
android:textColor="#000000"
android:textSize="18dp" />
<TextView
android:id="#+id/tvdesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvsubservices"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="Description"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/tvfulladdr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvdesc"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="New Text"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/custaddidposition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="position"
android:visibility="gone" />
</LinearLayout>
</RelativeLayout>
I want to get selected radio button position or value and id so that on button click I tried with but it always take first position. Can any one suggest me where am I doing wrong? I have to get selected radio button position so that I can get value from list of Objects. I have to send into next activity.
In adapter create a method which returns the object of selected position. Like :
public ListofAddressesDataModel getSelectedItem() {
return data.get(selectedPosition);
}
In activity, on click of the button call this method. Like :
#Override
public void onClick(View v) {
if(v.getId() == R.id.button) {
//Here you will get the selected item of which the radio button is checked
ListofAddressesDataModel selectedItem = ((ListofAddressesAdapter) add.getAdapter()).getSelectedItem();
}
}
EDIT :
Instead of below lines in getView() in adapter
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
just replace it with below line
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = position;
}
});

Button click event with Custom List view

I have two button at bottom i.e after listview ends.
I am using a custom listview which display list items with alternate colors.
how to set setOnClickListener for both button at bottom?
public class PieMainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRes = getResources();
new Random(new Date().getTime());
solbtn = (Button)findViewById(R.id.solution);
String recive ;
Bundle b = getIntent().getExtras();
final int piewrong=b.getInt("piewrong");
final int pieright=b.getInt("pieright");
final int pieunclick=b.getInt("pieunclick");
setContentView(R.layout.piechart_result);
recive = pieright+"/20";
mPie.setUnit(recive);
data1 = new ArrayList<String>();
fillData() ;
listtotal =getIntent().getStringArrayListExtra("listtotal");
timeuse =getIntent().getStringArrayListExtra("timeused");
adapter1 = new ListAdapter(this, data1, listtotal,timeuse);
ListView lvMain = (ListView) findViewById(R.id.list);
lvMain.setAdapter(adapter1);
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
int questionno = position+1;
Bundle b = new Bundle();
b.putInt("questionno",questionno);
b.putInt("piewrong",piewrong);
b.putInt("pieright",pieright);
b.putInt("pieunclick",pieunclick);
Intent in=new Intent(PieMainActivity.this,Solution.class);
in.putStringArrayListExtra("listtotal", (ArrayList<String>) listtotal);
in.putStringArrayListExtra("timeused", (ArrayList<String>) timeuse);
in.putExtras(b);
startActivity(in);
finish();
}
});
}
void fillData() {
for (int i = 1; i <= 20; i++) {
data1.add("Question " + i);
}
}
void fillcmp() {
for (int i = 1; i <= 20; i++) {
cmp.add("cmp " + i);
}
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.staritsolutions.apptitude"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:layout_weight="1.0">
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<Button
android:id="#+id/home"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Main Menu"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
<Button
android:id="#+id/solution"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Solutions"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
BaseAdapter file
public class ListAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
List<String> data1;
List<String> cmp;
List<String> timeused;
ListAdapter(Context context, List<String> data1 ,List<String> cmp ,List<String> timeused) {
ctx = context;
this.data1 = data1;
this.cmp = cmp;
this.timeused = timeused;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data1.size();
}
public int getCount1() {
return cmp.size();
}
#Override
public Object getItem(int position) {
return data1.get(position);
}
public Object getItem1(int position1) {
return cmp.get(position1);
}
#Override
public long getItemId(int position) {
return position;
}
public long getItemId1(int position1) {
return position1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.listitem, parent, false);
}
/*if (position % 2 == 0) {
view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
} else {
view.setBackgroundResource(R.drawable.artists_list_background_alternate);
}*/
TextView text = (TextView) view.findViewById(R.id.heading);
int no = position;
if(cmp.get(position).equals("GREEN"))
{
text.setTextColor(Color.parseColor("#00D50E"));
}else if(cmp.get(position).equals("RED"))
{
text.setTextColor(Color.parseColor("#e84040"));
}else
{
text.setTextColor(Color.parseColor("#B441E9"));
}
((TextView) view.findViewById(R.id.heading)).setText(data1.get(position));
((TextView) view.findViewById(R.id.duration)).setText(timeused.get(position));
return view;
//String.valueOf(value);
}
}
So these buttons are not part of your ListView? Well, than in your onCreate do something like:
solbtn = (Button)findViewById(R.id.solution);
solbth.setOnClickListener( toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourMethod();
}
});
And the same goes for the second button.
Or you can make your Activity implement View.OnClickListener, after doing this you can set your click listeners like this:
//this two lines in your OnCreate
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//somewhere later in the code
#Override
public void onClick(View v) {
//do something
}
Just add the clickListeners in your onCrete() method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
solbtn = (Button) findViewById(R.id.home);
homebtn = (Button) findViewById(R.id.solution);
solbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for solution button
}
});
homebtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for home button
}
});
.....
}

Get listitem from listview(Customized using Radio Button) when clicked on the Particular Item

I have prepared custom Listview in that i want to select one item from view so for that i have used RadioButton view for single choice item,but i customized it.Following is my total code ,because there may be error in the layout so please help me in solving this.
Activity:-
public class MainActivity extends Activity {
TextView tvEmpty;
ListView listView;
Spinner spnStage;
Button btnGet;
String sfrom;
ArrayList<String> arrayList;
StartFromAdapter arrayAdapter;
String[] stages = { "School", "Collage", "Office" };
String resultdata = "{\"Age\":{\"School\":[{\"Stage\":\"class1\",\"Name\":\"Classname1\"},{\"Stage\":\"class2\",\"Name\":\"ClassName2\"}],\"Collage\":[],\"Office\":[{\"Stage\":\"Office1\",\"Name\":\"Officename1\"},{\"Stage\":\"Office2\",\"Name\":\"Officename2\"}]}}";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvEmpty = (TextView) findViewById(R.id.emptytv);
listView = (ListView) findViewById(R.id.lstDemo);
spnStage = (Spinner) findViewById(R.id.spinner1);
btnGet = (Button) findViewById(R.id.button1);
ArrayAdapter<String> stageAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_spinner_item, stages);
stageAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStage.setAdapter(stageAdapter);
arrayList = new ArrayList<String>();
spnStage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
if (arrayList.size() > 0 && arrayList != null) {
arrayList.clear();
}
loadListView(parent.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = (Integer) v.getTag();
Log.i("SELECTED IN GET", "" + selectedPosition);
}
});
}
public void loadListView(String selectedItem) {
try {
JSONObject jObject = new JSONObject(resultdata);
JSONObject jAge = jObject.getJSONObject("Age");
JSONArray jSelectedItem = jAge.getJSONArray(selectedItem);
if (jSelectedItem.length() != 0) {
for (int i = 0; i < jSelectedItem.length(); i++) {
JSONObject jObj = jSelectedItem.getJSONObject(i);
arrayList.add(jObj.getString("Name"));
}
}
arrayAdapter = new StartFromAdapter(this, arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
listView.setEmptyView(tvEmpty);
Log.i("BEFORE LISTVIEW ONCLICK", "THIS IS ADDRESSLIST");
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
sfrom = ((RadioButton) v.findViewById(R.id.startfromrb))
.getText().toString();
Log.i("STARTFROM", sfrom);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Adapter:-
public class StartFromAdapter extends BaseAdapter {
ArrayList<String> detailsArrayList;
Context context;
int selectedPosition = 0;
public StartFromAdapter(Context context, ArrayList<String> detailsArrayList) {
this.detailsArrayList = detailsArrayList;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return detailsArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return detailsArrayList.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) {
LinearLayout rowLayout = null;
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(context).inflate(
R.layout.listitem_view, parent, false);
} else {
rowLayout = (LinearLayout) convertView;
}
RadioButton rbStartFrom = (RadioButton) rowLayout
.findViewById(R.id.startfromrb);
rbStartFrom.setChecked(position == selectedPosition);
rbStartFrom.setTag(position);
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
rbStartFrom.setText(detailsArrayList.get(position));
return rowLayout;
}
}
MAINLAYOUT:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
listitem_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:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/startfromrb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:focusable="false"
android:focusableInTouchMode="false"
android:lines="3"
android:paddingLeft="20dp"
android:text="RadioButton" />
</LinearLayout>
Update use code as per below
// On item click listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long itemId) {
RadioButton btn=(RadioButton) view.findViewById(R.id.startfromrb);
String sfrom = btn.getText().toString();
arrayAdapter.setSelected((int)itemId);
Log.i("STARTFROM", sfrom);
}
});
//Add below function in adapter class
public void setSelected(int selectedPosition){
this.selectedPosition=selectedPosition;
notifyDataSetChanged();
}
Also remove from adapter
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
And add android:clickable="false" and set selectedPosition to -1 by default
The first I see is, that You have to change the reference to the Views where You want to set the other views below :
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
But anyway, Your TextView is sitten directly above the listView, is this Your intention? If not, You have to set
android:layout_below="#+id/lstDemo"
Also, if You get any errors, please post the logcat output. If You just have problems with Your layout, please explain clear enough what exactly You want.
EDIT
try to get the selected item String like this:
final String item = (String) parent.getItemAtPosition(position);
loadListView(item);

Issues in Custom Gridview with Multiple Radiobutton with single selection in android

I implemented a Gridview with radiobutton here is my code:
row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="50px"
android:layout_height="50px"
android:layout_marginRight="10px" >
</ImageView>
<RadioButton
android:id="#+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5px"
android:textSize="15px" >
</TextView>
</LinearLayout>
My MainActivity.java File
public class Radio extends Activity {
ArrayList<ParserCategory>mList;
DatabaseConnectionAPI mApi;
ImageAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*** Get Images from SDCard ***/
// gridView1
mApi=new DatabaseConnectionAPI(getApplicationContext());
try {
mApi.createDataBase();
mApi.openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mList=mApi.getCategoryData();
final GridView gView1 = (GridView)findViewById(R.id.gridView1);
mAdapter=new ImageAdapter(Radio.this, mList);
gView1.setAdapter(mAdapter);
// Get Item Checked
Button btnGetItem = (Button) findViewById(R.id.btnGetItem);
btnGetItem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int count = gView1.getChildCount();
System.out.println("Count "+count);
for (int i = 0; i < count; i++) {
ViewGroup gridChild = (ViewGroup) gView1.getChildAt(i);
RadioButton rbtn = (RadioButton)gridChild.findViewById(R.id.radio);
if(rbtn.isChecked())
{
Log.d("Item "+String.valueOf(i), rbtn.getTag().toString());
System.out.println("ITEEMERM "+String.valueOf(i)+rbtn.getTag().toString());
Toast.makeText(Radio.this,rbtn.getTag().toString() ,2000).show();
}
}
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private ArrayList<ParserCategory> lis;
public ImageAdapter(Context c, ArrayList<ParserCategory> mList)
{
context = c;
lis = mList;
}
public int getCount() {
return lis.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.raddioshowimage, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.textView1);
String strPath = lis.get(position).toString();
// Get File Name
String fileName=lis.get(position).getCname();
textView.setText(lis.get(position).getCname());
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
RadioButton radiobtn = (RadioButton) convertView.findViewById(R.id.radio);
radiobtn.setTag(fileName);
return convertView;
}
}
}
When I run the above code it selects multiple items with radiobutton, but I want a single item selection when I click a button so any idea how can I solve it?

Categories

Resources