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;
}
Related
I have a Fragment that displays a Dialog.
Inside that Dialog there is a RadioGroup.
I tried to create a listener to this RadioGroup, but i didn't successed.
Fragment --> Dialog --> RadioGroup
I tried four ways:
OnCheckedChangeListener on RadioGroup.
OnClickListener on RadioGroup.
OnCheckedChangeListener on RadioButton.
OnClickListener on RadioButton
No one worked.
Here is my code:
The Dialog - layout:
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioGroup
android:id="#+id/bS_rg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:orientation="vertical">
<RadioButton
android:id="#+id/r_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="ID"
android:textSize="24sp" />
<RadioButton
android:id="#+id/r_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Title"
android:textSize="24sp" />
<RadioButton
android:id="#+id/r_genre"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Genre"
android:textSize="24sp" />
<RadioButton
android:id="#+id/r_author"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Author"
android:textSize="24sp" />
</RadioGroup>
<AutoCompleteTextView
android:id="#+id/c_bSearch"
android:layout_width="278dp"
android:layout_height="72dp"
android:singleLine="true"/>
</LinearLayout>
The Fragment - layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<de.codecrafters.tableview.TableView
android:id="#+id/tableView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
And the Fragment - code: (I marked where is the problem, the other code is not important)
package com.example.adiel.library_app_30;
import .....;
public class ShowAllBooks extends Fragment {
View v;
TableLayout table;
TableRow row;
String[] spaceProbeHeaders = {"ID", "Title"};
String[][] spaceProbes;
AutoCompleteTextView c_search;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.show_all_books, container, false);
setHasOptionsMenu(true);
/*
------The problem is here----
*/
LayoutInflater li = LayoutInflater.from(v.getContext());
View promptsView = li.inflate(R.layout.b_search_dialog, null);
c_search = (AutoCompleteTextView) promptsView.findViewById(R.id.c_bSearch);
RadioGroup rg = (RadioGroup) promptsView.findViewById(R.id.bS_rg);
rg.check(R.id.r_id);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
Log.d("Log", "Clicked");
}
});
rg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Log", "Clicked");
}
});
RadioButton r_id = (RadioButton) promptsView.findViewById(R.id.r_id);
r_id.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d("Log", "Clicked");
}
});
r_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Log", "Clicked");
}
});
/*
------Until here----
*/
final TableView<String[]> tb = (TableView<String[]>) v.findViewById(R.id.tableView);
tb.setColumnCount(2);
tb.setHeaderBackgroundColor(Color.parseColor("#2ecc71"));
Ask a = new Ask("books", "getAllCopiesOfBooks", null);
Client client = (Client) new Client(a, a.getIp(), v.getContext(), new Client.ClientReply() {
#Override
public void processFinish(Object output) {
if (output != null) {
ArrayList<CopyId> data = (ArrayList<CopyId>) output;
spaceProbes = new String[data.size()][2];
for (int i = 0; i < data.size(); i++) {
CopyId c = data.get(i);
spaceProbes[i][0] = String.valueOf(c.getId());
spaceProbes[i][1] = c.getTitle();
}
tb.setHeaderAdapter(new SimpleTableHeaderAdapter(v.getContext(), spaceProbeHeaders));
tb.setDataAdapter(new SimpleTableDataAdapter(v.getContext(), spaceProbes));
}
}
}).execute();
tb.addDataClickListener(new TableDataClickListener() {
#Override
public void onDataClicked(int rowIndex, Object clickedData) {
Toast.makeText(v.getContext(), ((String[]) clickedData)[0], Toast.LENGTH_SHORT).show();
Intent i = new Intent(v.getContext(), ShowBook.class);
i.putExtra("id", ((String[]) clickedData)[0]);
startActivity(i);
}
});
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.showallbooks_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_add:
return true;
case R.id.action_search:
search_func();
return true;
}
return super.onOptionsItemSelected(item);
}
public void search_func(){
final Dialog dialog = new Dialog(v.getContext());
dialog.setContentView(R.layout.b_search_dialog);
dialog.setTitle("Search");
dialog.show();
//RadioButton r_id = (RadioButton) promptsView.findViewById(R.id.r_id);
/*RadioButton r_title = (RadioButton) v.findViewById(R.id.r_title);
RadioButton r_genre = (RadioButton) v.findViewById(R.id.r_genre);
RadioButton r_author = (RadioButton) v.findViewById(R.id.r_author);*/
}
}
Here, in a listview I have added a custom row in which Checkbox and EditText are there and with a add button I just add multiple views to my listview. Adding is working perfectly but when it comes to removing part the checked items are not removing and apart from that suppose I selected two items, then two items from last deleted. I don't know whats going on with my code please help me.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
AdapterCustom customAdapter;
ArrayList<String> stringArrayList;
ListView listView;
ArrayList<Integer> listOfItemsToDelete;
AdapterCustom.ViewHolder item;
int POS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfItemsToDelete = new ArrayList<Integer>();
stringArrayList = new ArrayList<String>();
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
listView = (ListView) findViewById(R.id.list_item);
customAdapter = new AdapterCustom(MainActivity.this, R.layout.main, stringArrayList);
}
public void addItems(View v) {
stringArrayList.add("");
listView.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
public void removeItems(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
} else {
Log.i("Delete Pos", POS + "");
if (!listOfItemsToDelete.equals("")) {
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
}
}
}
AdapterCustom.java
public class AdapterCustom extends ArrayAdapter<String> {
Context context;
ArrayList<String> stringArrayList;
ArrayList<Boolean> positionArray;
MainActivity activity;
public AdapterCustom(Context context, int resourceId, ArrayList<String> arrayList) {
super(context, resourceId, arrayList);
this.context = context;
this.stringArrayList = arrayList;
positionArray = new ArrayList<Boolean>(stringArrayList.size());
for (int i = 0; i < stringArrayList.size(); i++) {
positionArray.add(false);
}
activity = new MainActivity();
}
#Override
public int getCount() {
return stringArrayList.size();
}
#Override
public String getItem(int position) {
return stringArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
EditText ediText;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
item = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.main, null);
item.ediText = (EditText) convertView.findViewById(R.id.ediText);
item.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
item.checkBox.setTag(new Integer(position));
convertView.setTag(item);
final View finalConvertView1 = convertView;
item.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
int getPosition = (Integer) compoundButton.getTag();
POS = getPosition;
listOfItemsToDelete.add(POS);
Log.i("position after check", POS + "");
Log.i("position check array", listOfItemsToDelete + "");
}
}
});
} else {
item = (ViewHolder) convertView.getTag();
}
item.checkBox.setTag(position);
return convertView;
}
}
activity_main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="10">
<Button
android:id="#+id/addBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="addItems"
android:text="Add New Item" />
<Button
android:id="#+id/goBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="goItems"
android:text="Go to Item" />
</LinearLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:drawSelectorOnTop="false"
android:visibility="visible" />
<Button
android:id="#+id/removeBtn"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:onClick="removeItems"
android:text="Remove Item" />
</LinearLayout>
main.xml
<LinearLayout
android:id="#+id/custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
android:weightSum="10">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<EditText
android:id="#+id/ediText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:background="#android:color/white"
android:hint="Type Anything You Want" />
</LinearLayout>
You only remove the item from the array. Try removing the item also from the list view adapter with adapter.remove(itemPosition);
What does mean
- j
in this code:
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
?
I think that:
for (String itemToRemove:listOfItemsToDelete) {
stringArrayList.remove(itemToRemove);
}
customAdapter.notifyDataSetChanged();
listOfItemsToDelete.clear();
would be appropriate.
After selecting the header checkbox all listview item checkbox not selected.
Selected listview checkbox items are not moved from list1 to list2.
Below is the full code
Home Activity class
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class HomeAct extends Activity {
List<DocItem> docDet1 = new ArrayList<DocItem>();
List<DocItem> docDet2 = new ArrayList<DocItem>();
ListView lv1, lv2;
Button btn1;
DocDetAdapter adapter1, adapter2;
int n = 0;
int marksValue;
int value = 0;
CheckBox boxheader;
ArrayList<Boolean> positionArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_act);
lv1 = (ListView) findViewById(R.id.lv_det1);
lv2 = (ListView) findViewById(R.id.lv_det2);
btn1 = (Button) findViewById(R.id.btn1);
boxheader = (CheckBox)findViewById(R.id.checkBoxHeader);
adapter1 = new DocDetAdapter(1);
adapter2 = new DocDetAdapter(2);
docDet1.add(new DocItem("1", "john", 20));
docDet1.add(new DocItem("2", "karan", 10));
docDet1.add(new DocItem("3", "james", 5));
docDet1.add(new DocItem("4", "shaun", 60));
docDet1.add(new DocItem("5", "jack", 50));
docDet1.add(new DocItem("6", "sam", 30));
docDet1.add(new DocItem("7", "tony", 6));
docDet1.add(new DocItem("8", "mark", 42));
lv1.setAdapter(adapter1);
lv2.setAdapter(adapter2);
positionArray = new ArrayList<Boolean>(docDet1.size());
for (int i = 0; i < docDet1.size(); i++) {
positionArray.add(false);
}
boxheader.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
checkBox.setChecked(true);
}
} else {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
checkBox.setChecked(false);
}
}
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
if (checkBox.isChecked()) {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 1111 " + i);
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 2222 " + docDet1.size());
if (docDet1.size() == 1) {
new AlertDialog.Builder(HomeAct.this)
.setTitle("Attention!")
.setMessage("Last name")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
docDet1.remove(0);
docDet2.add(new DocItem(docDet1.get(0).docNo, docDet1.get(0).name, docDet1.get(0).marks));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
}
}).show();
return;
}
docDet2.add(new DocItem(docDet1.get(i).docNo, docDet1.get(i).name, docDet1.get(i).marks));
docDet1.remove(i);
adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged();
} else {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 3333 none are checked ");
Toast.makeText(HomeAct.this, "Please select atleast one name", Toast.LENGTH_LONG).show();
}
}
}
});
}
DocItem findDocItem(String name) {
for (DocItem item : docDet2) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
DocItem findDocItem2(String name) {
for (DocItem item : docDet1) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
private class DocDetAdapter extends BaseAdapter {
int mode; // 1 or 2
public DocDetAdapter(int mode) {
this.mode = mode;
}
#Override
public int getCount() {
if (mode == 1)
return docDet1.size();
else
return docDet2.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.row_det, null);
TextView tvName = (TextView) convertView
.findViewById(R.id.tv_name);
TextView tvNo = (TextView) convertView.findViewById(R.id.tv_no);
TextView tvMarks = (TextView) convertView.findViewById(R.id.tv_marks);
CheckBox box = (CheckBox)convertView.findViewById(R.id.checkBoxRow);
DocItem invItem;
if (mode == 1)
invItem = docDet1.get(position);
else
invItem = docDet2.get(position);
tvNo.setText(invItem.docNo);
tvName.setText(invItem.name);
tvMarks.setText(invItem.marks + "");
box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
positionArray.set(position, true);
} else {
positionArray.set(position, false);
}
}
});
box.setChecked(positionArray.get(position));
return convertView;
}
}
}
DocItem class
public class DocItem {
public String docNo, name;
public Integer marks;
public DocItem(String docNo, String name, Integer marks) {
super();
this.docNo = docNo;
this.name = name;
this.marks = marks;
}
}
home_act.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" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="3"
android:text="Add" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="list 1"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/row_bg_transparent_white"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_tv_no"
style="#android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:gravity="center_vertical"
android:padding="10dp"
android:text="Sl no"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:text="Name"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_marks"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:paddingRight="3dp"
android:text="Marks"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/checkBoxHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select all" />
</LinearLayout>
<ListView
android:id="#+id/lv_det1"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="list 2"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<ListView
android:id="#+id/lv_det2"
android:layout_width="fill_parent"
android:layout_height="250dp" />
</LinearLayout>
row_det.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="wrap_content"
android:orientation="vertical" >
<View
android:id="#+id/v_doc_seperator"
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="#color/blue"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/row_bg_transparent_white"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_no"
style="#android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:gravity="center_vertical"
android:padding="10dp"
android:text="Sl no"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:text="Name"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_marks"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:paddingRight="3dp"
android:text="Marks"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/checkBoxRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
</LinearLayout>
Please find the below screenshots
If I select header checkbox(select all), only first five rows are selected
Remainig rows are not selected
If I select row 2 and row 3 and click on add I got wrong output(refer last screenshot)
row 2 and row 4 are added in list2 (but correct output is row 2 and row 3 should be added) after clicking on add all the checkboxes should be unchecked.
Please help me thanks in advance.
Try this:
public class HomeAct extends Activity {
List<DocItem> docDet1 = new ArrayList<DocItem>();
List<DocItem> docDet2 = new ArrayList<DocItem>();
ListView lv1, lv2;
Button btn1;
DocDetAdapter adapter1, adapter2;
int n = 0;
int marksValue;
int value = 0;
CheckBox boxheader;
ArrayList<Boolean> positionArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_act);
lv1 = (ListView) findViewById(R.id.lv_det1);
lv2 = (ListView) findViewById(R.id.lv_det2);
btn1 = (Button) findViewById(R.id.btn1);
boxheader = (CheckBox)findViewById(R.id.checkBoxHeader);
adapter1 = new DocDetAdapter(1);
adapter2 = new DocDetAdapter(2);
docDet1.add(new DocItem("1", "john", 20));
docDet1.add(new DocItem("2", "karan", 10));
docDet1.add(new DocItem("3", "james", 5));
docDet1.add(new DocItem("4", "shaun", 60));
docDet1.add(new DocItem("5", "jack", 50));
docDet1.add(new DocItem("6", "sam", 30));
docDet1.add(new DocItem("7", "tony", 6));
docDet1.add(new DocItem("8", "mark", 42));
lv1.setAdapter(adapter1);
lv2.setAdapter(adapter2);
positionArray = new ArrayList<Boolean>(docDet1.size());
for (int i = 0; i < docDet1.size(); i++) {
positionArray.add(false);
}
boxheader.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
/* int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
checkBox.setChecked(true);
} */
// Update DataSet instead of view
for (int i = 0; i < docDet1.size(); i++){
positionArray.set(i, true);
}
} else {
/* int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
checkBox.setChecked(false);
} */
// Update DataSet instead of view
for (int i = 0; i < docDet1.size(); i++){
positionArray.set(i, false);
}
}
// Update ListView after dataSet updated.
adapter1.notifyDataSetChanged();
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* int itemsCount = lv1.getChildCount(); */
// Get items from end to beginning of list.
// Otherwise position may be wrong after remove item.
for (int i = docDet1.size() - 1; i >= 0; i--) {
/* View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
if (checkBox.isChecked()) { */
if(positionArray.get(i)) {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 1111 " + i);
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 2222 " + docDet1.size());
if (docDet1.size() == 1) {
new AlertDialog.Builder(HomeAct.this)
.setTitle("Attention!")
.setMessage("Last name")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
docDet1.remove(0);
docDet2.add(new DocItem(docDet1.get(0).docNo, docDet1.get(0).name, docDet1.get(0).marks));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
}
}).show();
return;
}
docDet2.add(0, new DocItem(docDet1.get(i).docNo, docDet1.get(i).name, docDet1.get(i).marks));
docDet1.remove(i);
/* adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged(); */
} else {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 3333 none are checked ");
Toast.makeText(HomeAct.this, "Please select atleast one name", Toast.LENGTH_LONG).show();
}
}
// Reset all CheckBox data
for (int i = 0; i < positionArray.size(); i++){
positionArray.set(i, false);
}
// Update ListViews after all data updated.
adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged();
}
});
}
DocItem findDocItem(String name) {
for (DocItem item : docDet2) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
DocItem findDocItem2(String name) {
for (DocItem item : docDet1) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
private class DocDetAdapter extends BaseAdapter {
int mode; // 1 or 2
public DocDetAdapter(int mode) {
this.mode = mode;
}
#Override
public int getCount() {
if (mode == 1)
return docDet1.size();
else
return docDet2.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null) convertView = li.inflate(R.layout.row_det, null);
TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
TextView tvNo = (TextView) convertView.findViewById(R.id.tv_no);
TextView tvMarks = (TextView) convertView.findViewById(R.id.tv_marks);
CheckBox box = (CheckBox)convertView.findViewById(R.id.checkBoxRow);
DocItem invItem;
if (mode == 1)
invItem = docDet1.get(position);
else
invItem = docDet2.get(position);
tvNo.setText(invItem.docNo);
tvName.setText(invItem.name);
tvMarks.setText(invItem.marks + "");
box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
positionArray.set(position, true);
} else {
positionArray.set(position, false);
}
}
});
box.setChecked(positionArray.get(position));
return convertView;
}
}
}
Hope this help!
Because after checked you are adding on the array that contain in adapter and on scrolling it will refresh. So you should use interface here after checked or unchecked you should add status in main class and then notify your adapter and invalidate your listview.
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
}
});
.....
}
I have three views in sliding Fragment with Survey Questions having dynamic radiobuttons (the layout for all views are same, i am just repeating). I can get the data of selected radiobuttons from one screen, but how can i get the data of all selected radiobuttons from all screens ? Below is my working code
FragmentActivity.java
public class MainActivity extends FragmentActivity {
static final int ITEMS = 3;
MyAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
Button button = (Button) findViewById(R.id.first);
Button submitaldatabutton = (Button) findViewById(R.id.first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(ITEMS - 1);
}
});
submitaldatabutton = (Button) findViewById(R.id.submitalldata);
submitaldatabutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Get all data
}
});
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
switch (position) {
case 0: // Fragment # 0 - This will show image
return LayoutFragment.init(position);
case 1: // Fragment # 1 - This will show image
return LayoutFragment.init(position);
default:// Fragment # 2-9 - Will show list
return LayoutFragment.init(position);
}
}
//#Override
/*public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show image
return ImageFragment.init(position);
case 1: // Fragment # 1 - This will show image
return ImageFragment.init(position);
default:// Fragment # 2-9 - Will show list
return ArrayListFragment.init(position);
}
}*/
}
}
LayoutFragment.java
public class LayoutFragment extends Fragment {
int fragVal;
private String[] application = { "Country1", "Country2", "Country3", "Country4", "Country5", "Country6", "Country7", "Country8" };
private String[] device = { "Country9", "Country10", "Country11", "Country12", "Country13", "Country14", "Country15", "Country16" };
private RadioGroup radioGroup1;
private RadioGroup radioGroup2;
private RadioButton btn;
private RadioButton btn2;
private String text1;
private String text2;
RadioButton button1;
RadioButton button2;
Button selectall;
Context thiscontext;
static LayoutFragment init(int val) {
LayoutFragment truitonFrag = new LayoutFragment();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putInt("val", val);
truitonFrag.setArguments(args);
return truitonFrag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
thiscontext = container.getContext();
View layoutView = inflater.inflate(R.layout.activity_main, container, false);
Button myButton = (Button) layoutView.findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("");
// Get selected radiobuttons
if (radioGroup1.getCheckedRadioButtonId() != -1) {
text1 = btn.getText().toString();
Log.d("Button", "Text 1 : " + text1);
}
if (radioGroup2.getCheckedRadioButtonId() != -1) {
text2 = btn2.getText().toString();
Log.d("Button", "Text 2 : " + text2);
}
Toast.makeText(
thiscontext,
"Data Posting : APPLICATION : "
+ text1 + " \nDEVICE : " + text2,
Toast.LENGTH_LONG).show();
}
});
//Draw Radiobuttons
radioGroup1 = (RadioGroup) layoutView.findViewById(R.id.radio1);
radioGroup2 = (RadioGroup) layoutView.findViewById(R.id.radio2);
ViewGroup hourButtonLayout = (ViewGroup) layoutView.findViewById(R.id.radio1);
for (int i = 0; i < application.length; i++) {
button1 = new RadioButton(thiscontext);
button1.setId(i);
button1.setText(application[i]);
hourButtonLayout.addView(button1);
radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup mRadioGroup2,
int checkedId2) {
for (int i = 0; i < mRadioGroup2.getChildCount(); i++) {
btn = (RadioButton) mRadioGroup2.getChildAt(i);
int t = mRadioGroup2.getId();
System.out.println(t);
if (btn.getId() == checkedId2) {
text1 = btn.getText().toString();
Toast.makeText(thiscontext,
"You selected : " + text1,
Toast.LENGTH_SHORT).show();
return;
}
}
}
});
}
ViewGroup hourButtonLayout2 = (ViewGroup) layoutView.findViewById(R.id.radio2);
for (int i = 0; i < device.length; i++) {
button2 = new RadioButton(thiscontext);
button2.setId(i);
button2.setText(device[i]);
hourButtonLayout2.addView(button2);
radioGroup2
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup mRadioGroup,
int checkedId) {
for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
btn2 = (RadioButton) mRadioGroup.getChildAt(i);
int t = mRadioGroup.getId();
System.out.println(t);
if (btn2.getId() == checkedId) {
text2 = btn2.getText().toString();
Toast.makeText(thiscontext,
"You selected : " + text2,
Toast.LENGTH_SHORT).show();
return;
}
}
}
});
}
return layoutView;
}
}
activity_main.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:background="#fff">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000"
android:text="Select Question1"
android:textSize="18sp"/>
<Button
android:id="#+id/findSelected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="200dip"
android:orientation="vertical"
android:scrollbars="none" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="200dip"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginTop="5dip"
android:background="#fff"
android:checkedButton="#+id/sound" >
</RadioGroup>
</LinearLayout>
</ScrollView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:text="Select Question2"
android:textColor="#000"
android:textSize="18sp"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="360dip"
android:orientation="vertical"
android:scrollbars="none" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="560dip"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginTop="5dip"
android:background="#fff"
android:checkedButton="#+id/sound">
</RadioGroup>
</LinearLayout>
</ScrollView>
</LinearLayout>
fragment_pager.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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:measureWithLargestChild="true"
android:orientation="horizontal" >
<Button
android:id="#+id/first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First" >
</Button>
<Button
android:id="#+id/last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last" >
</Button>
<Button
android:id="#+id/submitalldata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit AllData" >
</Button>
</LinearLayout>
</LinearLayout>