In expandable list view set the data based on the parent. In this parent has child item selection, the selection set image view for each child item selection. But in this selection set the other parents child items.
Below code for parent value set.
#Override
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
GroupViewHolder groupViewHolder;
if(view==null){
groupViewHolder=new GroupViewHolder();
view=((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.category_listview_group_item,null);
groupViewHolder.name=(TextView)view.findViewById(R.id.category_listview_item_name);
groupViewHolder.nameIcon=(ImageView)view.findViewById(R.id.category_listview_item_icon);
groupViewHolder.progressBar = (ProgressBar)view.findViewById(R.id.categoryImageProgressBarlist);
groupViewHolder.rigtharrow=(ImageButton)view.findViewById(R.id.category_listview_item_onclick);
view.setTag(groupViewHolder);
} else {
groupViewHolder=(GroupViewHolder)view.getTag();
}
groupViewHolder.nameIcon =itemImage(view, R.id.category_listview_item_icon, data.get(i).getImageUrl(), groupViewHolder.progressBar);
groupViewHolder.name.setText(data.get(i).getName());
return view;
}
Below code for child item value set
#Override
public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
final ChildViewHolder childViewHolder;
String[] spinnerCount = {"1","2","3","4","5"};
if(view==null) {
childViewHolder = new ChildViewHolder();
view = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.category_listview_child_item,null);
childViewHolder.childName = (TextView)view.findViewById(R.id.listview_child_item_name);
childViewHolder.childNamePrice = (TextView)view.findViewById(R.id.listview_child_item_price);
childViewHolder.childNameIcon = (ImageView)view.findViewById(R.id.listview_child_item_icon);
childViewHolder.spinner = (Spinner)view.findViewById(R.id.spinner);
view.setTag(childViewHolder);
}
else {
childViewHolder=(ChildViewHolder)view.getTag();
}
childViewHolder.childNameIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!childViewHolder.childNameIcon.isSelected()) {
childViewHolder.childNameIcon.setBackgroundResource(R.mipmap.yellow_circle_list_item);
childViewHolder.childNameIcon.setSelected(true);
// childViewHolder.childNameIcon.setTag(R.mipmap.yellow_circle_list_item);
String quantity = childViewHolder.spinner.getSelectedItem().toString();
Products product = data.get(i).getProductsList().get(i1);
product.setQuantity(quantity);
dataHandler.addTempproducts(product);
} else {
childViewHolder.childNameIcon.setBackgroundResource(R.mipmap.black_circle_list_item);
childViewHolder.childNameIcon.setSelected(false);
// childViewHolder.childNameIcon.setTag(R.mipmap.black_circle_list_item);
dataHandler.removeTempProducts(data.get(i).getProductsList().get(i1));
Products product = data.get(i).getProductsList().get(i1);
product.setQuantity("1");
}
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item,spinnerCount);
childViewHolder.spinner.setAdapter(adapter);
childViewHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String spinnerCount = childViewHolder.spinner.getSelectedItem().toString();
Products product = data.get(i).getProductsList().get(i1);
ArrayList<Products> productList = new ArrayList<Products>();
productList = dataHandler.getTempproducts();
if (childViewHolder.childNameIcon.isSelected()) {
for (int k = 0; k < productList.size(); k++) {
if (data.get(i).getProductsList().get(i1).getId() == productList.get(k).getId()) {
productList.get(k).setQuantity(spinnerCount);
}
}
} else {
product.setQuantity(spinnerCount);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
childViewHolder.childName.setText(data.get(i).getProductsList().get(i1).getName());
if(data.get(i).getProductsList().get(i1).getPrice().isEmpty()) {
childViewHolder.childNamePrice.setText(data.get(i).getProductsList().get(i1).getPrice());
} else {
childViewHolder.childNamePrice.setText(data.get(i).getProductsList().get(i1).getPrice()+"/-");
}
return view;
}
Please Help me , i am struct here.......
Related
I'm creating an android app, in which I'm using recyclerView and the row of recyclerView is having editText.
This is my ReadingAdapter class
public class ReadingAdapter extends RecyclerView.Adapter<ReadingAdapter.ViewHolder> implements AdapterView.OnItemSelectedListener {
Context context;
String valOpenReading, valClosReading, valConsumption;
private List<ReadingData> readingList;
static String[] arrValOpenRead, arrValClosRead, arrValConsumption;
public ReadingAdapter(Context context, List<ReadingData> readingList) {
this.context = context;
this.readingList = readingList;
arrValOpenRead = new String[readingList.size()];
arrValClosRead = new String[readingList.size()];
arrValConsumption = new String[readingList.size()];
}
#Override
public ReadingAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reading_sheet_layout, parent, false);
return new ReadingAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final ReadingAdapter.ViewHolder holder, final int position) {
ReadingData tempData = readingList.get(position);
holder.pdtName.setText(tempData.pdtName);
holder.keyId.setText("Key "+tempData.keyId);
holder.etClosRead.addTextChangedListener(new TextWatcher() {
boolean ignore = false;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (ignore)
return;
ignore = true;
valOpenReading = holder.etOpenRead.getText().toString();
arrValOpenRead[position] = valOpenReading;
valClosReading = s.toString().equals("") ? "0": s.toString();
arrValClosRead[position] = valClosReading;
if (!valOpenReading.equals("")) {
if (Integer.parseInt(valClosReading) < Integer.parseInt(valOpenReading)) {
Toast.makeText(context, "Check once! closing reading should be more than opening reading!", Toast.LENGTH_LONG).show();
valConsumption = "0";
holder.consumption.setText("");
} else {
valConsumption = (Integer.parseInt(valClosReading) - Integer.parseInt(valOpenReading))+"";
arrValConsumption[position] = valConsumption;
holder.consumption.setText(valConsumption);
}
} else
Toast.makeText(context, "Please fill the opening reading!", Toast.LENGTH_SHORT).show();
ignore = false;
}
});
}
#Override
public int getItemCount() {
return readingList.size();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView pdtName, keyId, consumption;
EditText etOpenRead, etClosRead;
public ViewHolder(View view) {
super(view);
pdtName = (TextView)view.findViewById(R.id.txt_list_pdt_supp);
keyId = (TextView)view.findViewById(R.id.key_set);
etOpenRead = (EditText)view.findViewById(R.id.open_val_set);
etClosRead = (EditText)view.findViewById(R.id.clos_val_set);
consumption = (TextView)view.findViewById(R.id.consumption_val);
}
}
}
This is my ReadingData.java
public class ReadingData {
String pdtName, keyId, openReading, closReading, consumption;
public ReadingData(String pdtName, String keyId) {
this.pdtName = pdtName;
this.keyId = keyId;
}
}
Here, if I enter value in the starting items of the recyclerView then as I scroll up the items to the bottom of the list, the last item will have that value.
Please ignore the quality of image as we can't upload above of 2MiB of snap.
Here the views are recycled as the list is scrolled. How to prevent the copying values to the other item in the list.
And that Toast is also repeated several times. How to stop this.
update:
By the suggetion of LQ Gioan through the SO question How ListView's recycling mechanism works , I got the logic how ListView actually works with recycling of views.
But I'm not sure whether the recyclerView also works same.
But here in my case, how can I implement this process. pls someone help me here.
RecyclerView reuse views, in fact it only generate the as many as views that is visible on the screen. so it's expected if you can see a value you set for other rows
The solution would be set all attributes of the view that you are changing to default or whatever the row should present from your data set
So put addTextChangedListener insode ViewHolder constructor(you can get position by calling getAdapterPosition()) for better performance and set the editText value inside onBindViewHolder method from your data set
Your Activity Code:
ListView listview = (ListView) findViewById(R.id.list_view);
listview.setItemsCanFocus(true);
Adapter adapter = new Adapter (YourActivity.this, YourArrayList);
listview .setAdapter(adapter);
Adapter class
public class Adapter extends BaseAdapter {
// Declare Variables \\
Context mContext;
LayoutInflater inflater;
Activity act;
String[] temp;
public Adapter(Context context, ArrayList<String> list) {
mContext = context;
inflater = LayoutInflater.from(mContext);
act = (Activity) context;
//-------Temp String Array-------\\
temp = new String[this.count];
for (int i = 0; i < this.count; i++) {
temp[i] = list.get(i);
}
//---------------------------\\
}
public class ViewHolder {
TextView optionTitle;
EditText optionText;
int ref;
}
#Override
public int getCount() {
return list.size;
}
#Override
public Object getItem(int position) {
return temp[position];
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.lv_items_add_ques_options_mcq, null);
holder.optionTitle = (TextView) view.findViewById(R.id.add_ques_opts_count_mcq_tv);
holder.optionText = (EditText) view.findViewById(R.id.add_ques_opts_title_mcq_et);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.ref = position;
holder.optionTitle.setText(getCharForNumber(position) + ":");
holder.optionText.setText(temp[position]);
holder.optionText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
temp[holder.ref] = arg0.toString().trim();
}
});
return view;
}
public void getList() {
StaticValues.arrayListOptions = new ArrayList<String>(Arrays.asList(temp));
StaticValues.arrayListOptionsCount = new ArrayList<String>();
for (int i = 0; i < count; i++) {
StaticValues.arrayListOptionsCount.add(String.valueOf(i+1));
Log.e("err_al", StaticValues.arrayListOptions.get(i));
Log.e("err_al", StaticValues.arrayListOptionsCount.get(i));
}
}
private String getCharForNumber(int i) {
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
if (i > 25) {
return null;
}
return Character.toString(alphabet[i]);
}}
is it possible to call a method in my CustomAdapter to set a checkbox Visible/Gone by clicking on an Element on my Fragments Listview? Ive got those two methods:
public void setCheckBoxSelectItemVisible(){
checkBoxSelectItem.setVisibility(View.VISIBLE);
return;
}
public void setCheckBoxSelectItemGone(){
checkBoxSelectItem.setVisibility(View.GONE);
return;
}
But How do I access them from my Fragment? Or do I have do chose another way?
(I want to set the checkbox visible by after "long click" on one of the ListView Elements)
Fragment:
public class ListViewFragment extends Fragment {
[...]
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
getActivity().setTitle(getString(R.string.listView));
registerForContextMenu(view);
final Context context = getContext();
mydb = new DbHelper(context);
locationpicker = (Spinner) view.findViewById(R.id.spinner_locations);
roomnr = (EditText) view.findViewById(R.id.editText_roomNr);
Drawable drawableForFabAdd = getResources().getDrawable(R.drawable.ic_add);
((MainActivity) getActivity()).fabmain.setImageDrawable(drawableForFabAdd);
((MainActivity) getActivity()).fabmain.animate().translationY(0);
((MainActivity) getActivity()).fabmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).scanQRCode();
((MainActivity) getActivity()).loadListViewFragment();
}
});
((MainActivity) getActivity()).fabdelete.animate().translationY(0);
final String locationNamesFromTableArray = mydb.getLocationNames();
if(!locationNamesFromTableArray.isEmpty()){
String[] roomNumbersFromTableArrayFinal = locationNamesFromTableArray.split("\t");
ArrayAdapter<String> adapter_locations;
adapter_locations = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, roomNumbersFromTableArrayFinal);
locationpicker.setAdapter(adapter_locations);
setFabdeleteVisible(listViewOk);
}
locationpicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
actualLocation = locationpicker.getSelectedItem().toString();
locationOk = true;
setFabsVisible(roomNrOk, true, listViewOk);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
roomnr.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
Pattern p = Pattern.compile("^[0-9]{3}$");
Matcher m = p.matcher(s);
roomNrOk = m.find();
setFabsVisible(roomNrOk, locationOk, listViewOk);
}
});
dataList = mydb.getElementsWithoutRoom();
if (!dataList.isEmpty()) {
final String[] dataListArray = dataList.split("\n");
Log.d("DATALIST", dataListArray[0]);
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
final ListView dataListListView = (ListView) view.findViewById(R.id.listView_datalist);
dataListListView.setAdapter(dataListAdapter);
dataListListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
((MainActivity) getActivity()).fabmain.animate().translationY(300);
}
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
((MainActivity) getActivity()).fabmain.animate().translationY(0);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
listViewOk = true;
setFabsVisible(roomNrOk, locationOk, true);
setFabdeleteVisible(listViewOk);
dataListListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedFromList = (dataListListView.getItemAtPosition(position).toString());
selectedElementArray = selectedFromList.split("\t");
dataListListView.showContextMenu();
}
});
dataListListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
(CustomListAdapter).setCheckBoxSelectItemVisible();
return true;
}
});
[...]
return view;
}
public void reloadListViewFragment(){
Fragment fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment = new ListViewFragment();
ft.replace(R.id.container, fragment);
ft.commitAllowingStateLoss();
}
[...]
}
CustomAdapter:
class CustomListAdapter extends ArrayAdapter<String> {
String doubleTab = "\t\t";
CheckBox checkBoxSelectItem;
public CustomListAdapter(Context context, String[] dataListFinal) {
super(context, R.layout.list_item_datalist ,dataListFinal);
}
public String allElementsAdapter = "";
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.list_item_datalist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_product);
TextView textViewlabel = (TextView) customView.findViewById(R.id.list_item_datalist_label_textview);
TextView textViewdetails1 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_1);
TextView textViewdetails2 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_2);
checkBoxSelectItem = (CheckBox) customView.findViewById(R.id.checkBox_Item);
String singleListItem = getItem(position);
String[] singleListItemArray = singleListItem.split("\t");
String id = singleListItemArray[0];
String product = singleListItemArray[1];
allElementsAdapter = product + label + serial + mac + daaid + bill;
switch (product) {
case "Pc":
image.setImageResource(R.drawable.icon_pc_circle);
break;
case "Laptop":
image.setImageResource(R.drawable.icon_laptop_circle);
break;
}
String details1 = serial +doubleTab+ mac;
String details2 = daaid +doubleTab+ bill;
textViewlabel.setText(label);
textViewdetails1.setText(details1);
textViewdetails2.setText(details2);
return customView;
}
public String getAllElements(){
return allElementsAdapter;
}
public void setCheckBoxSelectItemVisible(){
checkBoxSelectItem.setVisibility(View.VISIBLE);
return;
}
public void setCheckBoxSelectItemGone(){
checkBoxSelectItem.setVisibility(View.GONE);
return;
}
}
first change your Custom Adapter constructor with following
ArrayList<Boolean> mIsVisible;
public CustomListAdapter(Context context, String[] dataListFinal,ArrayList<Boolean> isVisible) {
super(context, R.layout.list_item_datalist ,dataListFinal);
mIsVisible = isVisible;
}
then modify getView()
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.list_item_datalist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_product);
TextView textViewlabel = (TextView) customView.findViewById(R.id.list_item_datalist_label_textview);
TextView textViewdetails1 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_1);
TextView textViewdetails2 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_2);
checkBoxSelectItem = (CheckBox) customView.findViewById(R.id.checkBox_Item);
String singleListItem = getItem(position);
String[] singleListItemArray = singleListItem.split("\t");
String id = singleListItemArray[0];
String product = singleListItemArray[1];
allElementsAdapter = product + label + serial + mac + daaid + bill;
switch (product) {
case "Pc":
image.setImageResource(R.drawable.icon_pc_circle);
break;
case "Laptop":
image.setImageResource(R.drawable.icon_laptop_circle);
break;
}
String details1 = serial +doubleTab+ mac;
String details2 = daaid +doubleTab+ bill;
textViewlabel.setText(label);
textViewdetails1.setText(details1);
textViewdetails2.setText(details2);
if(mIsVisible.get(position)){
checkBoxSelectItem.setVisibility(View.VISIBLE);
}else{
checkBoxSelectItem.setVisibility(View.GONE);
}
return customView;
}
After that modify your activity CustomAdapter creation part
final ArrayList<Boolean> isVisible=new ArrayList<Boolean>();
for(int count =0 ;count<dataListArray.length; count++){
isVisible.add(false);
}
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray, isVisible);
And last modify listener part
dataListListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(isVisible.get(position))
isVisible.set(position,false);
else
isVisible.set(position,true);
dataListAdapter.notifyDataSetChanged();
return true;
}
});
Done...!!!!!
It works with ((BaseAdapter)dataListAdapter).notifyDataSetChanged();
I have a ListView that is within a Fragment. In the onCreateView section I have set a onItemClickListener for the list, which highlights the selected item in the ListView. I have set two ImageButtons that navigate up and down the list. On selection a new Row is inflated that has its TextView's set to the content of the select item (for the purpose of retaining the highlighted selected state). However I am having difficulty adding that item back to the list. The app will not compile due to the line routines.add(selectedPos-1, str); it wants wants int location, Routine object. I believe the issue is with my construction of my SelectedAdapter class, but I have been unable to determine what to change/pass with regard to the Object.
IE:
public SelectedAdapter(Context context, int textViewResourceId,List objects) {
super(getActivity(), R.layout.listview_routines, routines); }
I would greatly appreciate any input as how to correct this issue; as well as any advice if there is a better way to maintain a selected state. Thanks for your help.
Fragment:
public static class FragmentRoutine extends Fragment {
DatabaseHandler db;
private ListView routineListView;
private List<Routine> routines = new ArrayList<Routine>();
ArrayAdapter<Routine> routineAdapter;
Routine longClickedItemRoutines;
private SelectedAdapter selectedAdapter;
public FragmentRoutine() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.routines,
container, false);
db = new DatabaseHandler(getActivity().getApplicationContext());
routineListView = (ListView) rootView.findViewById(R.id.routineList);
registerForContextMenu(routineListView);
db.closeDB();
if (db.getExerciseCount() != 0)
routines.clear();
routines.addAll(db.getAllRoutines());
populateList();
selectedAdapter = new SelectedAdapter(this.getActivity(), 0, routines);
selectedAdapter.setNotifyOnChange(true);
routineListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemRoutines = routines.get(position);
return false;
}
});
routineListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view,
int position, long id) {
selectedAdapter.setSelectedPosition(position);
}
});
routineListView.post(new Runnable() {
#Override
public void run() {
routineListView.setItemChecked(0, true);
}
});
// move up event handler
ImageButton btnMoveUp = (ImageButton) rootView.findViewById(R.id.btnMoveUp);
btnMoveUp.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveUp();
}
});
// move down event handler
ImageButton btnMoveDown = (ImageButton) rootView.findViewById(R.id.btnMoveDown);
btnMoveDown.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveDown();
}
});
setHasOptionsMenu(true);
return rootView;
}
// Move selected item "up" in the ViewList.
private void moveUp(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos > 0 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
//Problem Line Below
routines.add(selectedPos-1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos-1);
}
}
// Move selected item "down" in the ViewList.
private void moveDown(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos < routines.size()-1 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
routines.add(selectedPos+1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos+1);
}
}
public class SelectedAdapter extends ArrayAdapter<Routine>{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(getActivity(), R.layout.listview_routines, routines);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi
= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.selected_row, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
return(v);
}
}
private void populateList() {
routineAdapter = new SaveListAdapterT();
routineListView.setAdapter(routineAdapter);
}
public class SaveListAdapterT extends ArrayAdapter<Routine> {
public SaveListAdapterT() {
super(getActivity(), R.layout.listview_routines, routines);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_routines, parent, false);
Routine currentToDoSave = routines.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(currentToDoSave.getTagName());
return view;
}
}
}
I have an ExpandableListView on a fragment and when I choose an item I am changing the background and text colour of this item (TextView). This works fine. However when I collapse the group which contains the currently selected item, the selection is lost. How can I stop this from happening/set the selected item back to what it should be?
I have tried messing around with the onGroupExpand/CollapseListener's but not had any success. For example I have tried this:
_list.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
_list.setItemChecked(_activePosition, true);
}
});
Note: _list and _activePosition are declared at class level.
Here is my code for setting the checked item, from the examples I've seen I think this is standard practice, but please advise if not as I'm new to android.
HelpItemsFragment.java
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final List<HelpCategory> itemList = new ArrayList<HelpCategory>();
HelpCategory helpCategory;
//replace this with database stuff later
helpCategory = new HelpCategory();
helpCategory.setTitle("Group 1");
helpCategory.addHelpItem(new HelpItem((long) 1, "1.1", "Details for 1.1"));
helpCategory.addHelpItem(new HelpItem((long) 1, "1.2", "Details for 1.2"));
helpCategory.addHelpItem(new HelpItem((long) 1, "1.3", "Details for 1.3"));
itemList.add(helpCategory);
helpCategory = new HelpCategory();
helpCategory.setTitle("Group 2");
helpCategory.addHelpItem(new HelpItem((long) 2, "2.1", "Details for 2.1"));
helpCategory.addHelpItem(new HelpItem((long) 2, "2.2", "Details for 2.2"));
helpCategory.addHelpItem(new HelpItem((long) 2, "2.3", "Details for 2.3"));
itemList.add(helpCategory);
HelpExpandableListAdapter listAdapter = new HelpExpandableListAdapter(this.getActivity(), itemList);
_list.setAdapter(listAdapter);
_list.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition));
HelpItem helpItem = itemList.get(groupPosition).getHelpItemList().get(childPosition);
_activePosition = index;
_callback.onItemSelected(null, helpItem.getTitle(), helpItem.getDetail(), _activePosition);
parent.setItemChecked(index, true);
return true;
}
});
Adapter class HelpExpandableListAdapter should be like
public class HelpExpandableListAdapter extends BaseExpandableListAdapter {
private LayoutInflater inflater;
private ArrayList<CategoryGroup> mParent;
public ExpandableListItems(Context context, ArrayList<CategoryGroup> parent) {
mParent = parent;
inflater = LayoutInflater.from(context);
}
#Override
//counts the number of parent items so the list knows how many times calls getGroupView() method
public int getGroupCount() {
return mParent.size();
}
#Override
//counts the number of children items so the list knows how many times calls getChildView() method
public int getChildrenCount(int i) {
return mParent.get(i).getArrayChildren().size();
}
#Override
//gets the title of each parent/group
public Object getGroup(int i) {
return mParent.get(i).getTitle();
}
#Override
//gets the name of each item
public Object getChild(int i, int i1) {
return mParent.get(i).getArrayChildren().get(i1);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
//in this method you must set the text to see the parent/group on the list
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
if (view == null) {
System.out.println("i: " + i + "; b: " + b );
view = inflater.inflate(R.layout.grouprow, viewGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.rowname);
//"i" is the position of the parent/group in the list
textView.setText(getGroup(i).toString());
//return the entire view
return view;
}
#Override
//in this method you must set the text to see the children on the list
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
if (view == null) {
view = inflater.inflate(R.layout.childrow, viewGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.grpchild);
//"i" is the position of the parent/group in the list and
//"i1" is the position of the child
textView.setText(mParent.get(i).getArrayChildren().get(i1));
//return the entire view
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
/* used to make the notifyDataSetChanged() method work */
super.registerDataSetObserver(observer);
}
}
Group class
public class CategoryGroup {
private String mTitle;
private ArrayList<String> mArrayChildren;
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public ArrayList<String> getArrayChildren() {
return mArrayChildren;
}
public void setArrayChildren(ArrayList<String> mArrayChildren) {
this.mArrayChildren = new ArrayList(mArrayChildren);
}
}
In the onCreateView()
ArrayList<CategoryGroup> arrayParentsGroups = new ArrayList<CategoryGroup>();
arrayParentsGroups = createGroupList();
listAdapter = new HelpExpandableListAdapter(this, arrayParentsGroups);
_list.setAdapter(listAdapter);
private List createGroupList() {
ArrayList arrayParents = new ArrayList();
for( int i = 0 ; i < 10 ; ++i ) { // 10 groups........
CategoryGroup parent = new CategoryGroup();
parent.setTitle("Group row" + i);
ArrayList<String> arrayChildren = new ArrayList<String>();
for (int j = 0; j < 3; j++) {
arrayChildren.add("Child row" + j);
}
parent.setArrayChildren(arrayChildren);
arrayParents.add(parent);
}
return arrayParents;
}
im a noob to android and i am populating a listview with an arrayilst and custom adapter. I want setup my listview onClickListener to execute commands based to the the items populating the listview. the listview is dynamically populated with items from the arraylist. I have tried the position and id parameters with no luck. Any help is greatly appreciated.
How I instantiate listview, arraylist, and adapter
portfoliolist = (ListView) findViewById(R.id.listViewPortfolios);
users = new ArrayList<PortfolioRecord>();
portfoliolist.setAdapter(new UserItemAdapter(this, R.layout.simplerow, users));
portfoliolist.setOnItemClickListener(this);
My Custom Adapter.
public class UserItemAdapter extends ArrayAdapter<PortfolioRecord> {
private ArrayList<PortfolioRecord> users;
public UserItemAdapter(Context context, int textViewResourceId, ArrayList<PortfolioRecord> users) {
super(context, textViewResourceId, users);
this.users = users;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.simplerow, null);
}
PortfolioRecord user = users.get(position);
if (user != null) {
TextView portfolioname = (TextView) v.findViewById(R.id.portfolioname);
TextView currentvalue = (TextView) v.findViewById(R.id.currentvalue);
if (portfolioname != null) {
portfolioname.setText(user.portfolioname);
}
if(currentvalue != null) {
currentvalue.setText("Current Value: " + user.currentvalue );
}
}
return v;
}
}
public class PortfolioRecord {
public String portfolioname;
public String currentvalue;
public PortfolioRecord(String portfolioname, String currentvalue) {
this.portfolioname = portfolioname;
this.currentvalue = currentvalue;
}
}
How i add items to arraylist:
user1 = new PortfolioRecord(pn10, denomination10+portfoliovalue10);
users.add(user1);
I have added Usernull, user1 and user2 to my arraylist. How do i identify these items? I've tried the folowing code with no luck
public void onItemClick(AdapterView parent, View itemClicked, int position,
long id) {
TODO Auto-generated method stub
switch(parent.getId()){
case R.id.listViewPortfolios:
if(portfoliolist.getSelectedItem()==usernull){
openCustomDialog();
}else if(portfoliolist.getSelectedItem()==user1){
whichportfolio=1;
}else if(portfoliolist.getSelectedItem()==user2){
whichportfolio=2;
}
break;}}
No need to implement OnItemSelectedListener. Just use this within the existing OnItemClick method:
public void onItemClick(AdapterView parent, View itemClicked, int position,
long id) {
// TODO Auto-generated method stub
PortfolioRecord user = users.get(position);
// I'm not certain what this code block does...
if(user.equals(usernull)){
openCustomDialog();
}else if(user.equals(user1)){
whichportfolio=1;
}else if(user.equals(user2)){
whichportfolio=2;
}}
supposing your portfolioRecord object has the following: getTypeofUser()
portfoliolist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
String typeofUser =users.get(position).getTypeofUser();
if(typeofUser == user1 ){
whichportfolio=1;
}
}
});
I recommend changing to a OnItemSelectedListener and then you could simply fetch the PortfolioRecord with:
listView.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView parent, View view, int position, long id) {
// Get the user (PortfolioRecord) that was selected
PortfolioRecord user = users.get(position);
// I'm not certain what this code block does...
if(user.equals(usernull)){
openCustomDialog();
}else if(user.equals(user1)){
whichportfolio=1;
}else if(user.equals(user2)){
whichportfolio=2;
}
}
});