My code java. I'm getting data from the intent as an array. I am using arraylist,listview and custom adapter. I can show the incoming data using listview. I want the item I clicked to be deleted. The name of my delete button "deleteshop" in customadapter. How can I do that ?
My code;
final ListView list = findViewById(R.id.list);
final ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
final String[] cartList = getIntent().getStringArrayExtra("saleData");
arrayList.add(new SubjectData("", ""));
final int cartListLength = cartList.length;
int counter = 0;
String lastItem = "";
for (String e : cartList) {
counter += 1;
if (e == "" || e == null) {
lastItem = cartList[counter-3];
break;
}
String productPhoto = "";
switch (e) {
case "1 PC GREEN COLA x 10.00 TL":
productPhoto = "cc";
break;
default:
productPhoto = "";
break; }
arrayList.add(new SubjectData(e, productPhoto));;
}
arrayList.remove(arrayList.size()-1);
arrayList.remove(arrayList.size()-1);
arrayList.add(new SubjectData("*** GRAND TOTAL TL:" + lastItem + " ***", "arrowgreen"));
arrayList.add(new SubjectData("", ""));
arrayList.add(new SubjectData("", ""));
final CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);
SubjectData model class:
String SubjectName;
String Image;
public SubjectData(String subjectName, String image) {
this.SubjectName = subjectName;
this.Image = image;
}
Customadapter;
class CustomAdapter implements ListAdapter {
ArrayList<SubjectData> arrayList;
Context context;
public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {
this.arrayList=arrayList;
this.context=context;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SubjectData subjectData=arrayList.get(position);
if(convertView==null){
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView=layoutInflater.inflate(R.layout.list_row, null);
TextView tittle=convertView.findViewById(R.id.title);
ImageView imag=convertView.findViewById(R.id.list_image);
ImageView
deleteshop=convertView.findViewById(R.id.deleteshop);
deleteshop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Deneme",
Toast.LENGTH_SHORT).show();
}
});
tittle.setText(subjectData.SubjectName);
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(subjectData.Image, "drawable",
context.getPackageName());
imag.setImageResource(resourceId);
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return arrayList.size();
}
#Override
public boolean isEmpty() {
return false;
}
listview design;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip">
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip" />
</LinearLayout>
<TextView
android:id="#+id/title"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:gravity="center"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
<ImageView
android:layout_gravity="center"
android:id="#+id/deleteshop"
android:src="#drawable/negative"
android:layout_width="25dp"
android:layout_height="25dp" ></ImageView>
</LinearLayout>
If you want to delete clicked item from your list view then you can use this code .I tested and its deleting smoothly , after deleting its updating list also.
CustomAdapter customAdapter = new CustomAdapter(this,R.layout.list_row, arrayList);
list.setAdapter(customAdapter);
// after setting adapter put this code
// and update your ui again using set adapter
Log.e("Custom",""+arrayList.size());
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
arrayList.remove(i);
list.setAdapter(customAdapter);
}
});
This is not a best solution but ulternative , suppose if you want to update your adapter on click of deletebutton first create one interface , here is sample
public interface MyInterface{
public void deleteItem(int pos);
}
Now in your main activity use like this MainActivity extends AppCompatActivity implements MyInterface and place your interface method public void deleteItem(int pos){ arrayList.remove(pos); list.setAdapter(customAdapter); }
After that call this method from your adapter like below
deleteshop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Delete",
Toast.LENGTH_SHORT).show();
//Actually change your list of items here
if (context instanceof SampleList) {
((MainActivity)context).deleteItem(position);
}
}
});
Related
I am searching for a way to load data into an Expandale List View, the output I want to resemble the one of the picture attached here
In order this to be done dynamically, is it better to be read from a csv? Or to create a DB? Furthermore, on a sub-item press, I want a ScrollView to appear.
Here is the code so far:
The layout of the activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ExpandableListView
android:id= "#+id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
The itemlayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/grp_child"
android:paddingLeft="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And the subitem:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/row_name"
android:paddingLeft="50dp"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
In the activity, I have hardcoded some values so far, using some tutorials I came across:
public void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photographers);
SimpleExpandableListAdapter expListAdapter =
new SimpleExpandableListAdapter(
this,
createGroupList(),
R.layout.group_row,
new String[] { "Group Item" },
new int[] { R.id.row_name },
createChildList(),
R.layout.child_row,
new String[] {"Sub Item"},
new int[] { R.id.grp_child}
);
setListAdapter( expListAdapter );
}catch(Exception e){
System.out.println("Errrr +++ " + e.getMessage());
}
}
/* Creating the Hashmap for the row */
#SuppressWarnings("unchecked")
private List createGroupList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < 15 ; ++i ) { // 15 groups........
HashMap m = new HashMap();
m.put( "Group Item","Group Item " + i ); // the key and it's value.
result.add( m );
}
return (List)result;
}
#SuppressWarnings("unchecked")
private List createChildList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < 15 ; ++i ) { // this -15 is the number of groups(Here it's fifteen)
/* each group need each HashMap-Here for each group we have 3 subgroups */
ArrayList secList = new ArrayList();
for( int n = 0 ; n < 3 ; n++ ) {
HashMap child = new HashMap();
child.put( "Sub Item", "Sub Item " + n );
secList.add( child );
}
result.add( secList );
}
return result;
}
public void onContentChanged () {
System.out.println("onContentChanged");
super.onContentChanged();
}
/* This function is called on each child click */
public boolean onChildClick( ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
System.out.println("Inside onChildClick at groupPosition = " + groupPosition +" Child clicked at position " + childPosition);
return true;
}
/* This function is called on expansion of the group */
public void onGroupExpand (int groupPosition) {
try{
System.out.println("Group expanding Listener => groupPosition = " + groupPosition);
}catch(Exception e){
System.out.println(" groupPosition Errrr +++ " + e.getMessage());
}
}
I am wondering if it is a good idea to store the data I want to show in separate csv files (one storing the data for the items, one for the subitems. one for the extra information in the ScrollView), to have id-s for identification and to directly read from the CSVs with the OpenCSVReader?
I would appreciate any pieces of advice,
Thanks
create adapter for your expandable listView. like that
public class ExpandableAdapter extends BaseExpandableListAdapter {
private final Context context;
private final List<Menu> parentObjects;
public ExpandableAdapter(Context context, ArrayList<Menu> parentObjects) {
this.context = context;
this.parentObjects = parentObjects;
}
#Override
public int getGroupCount() {
return parentObjects.size();
}
#Override
public int getChildrenCount(int i) {
return parentObjects.get(i).childMenu.size();
}
#Override
public Menu getGroup(int i) {
return parentObjects.get(i);
}
#Override
public Menu.ChildMenu getChild(int i, int i2) {
return parentObjects.get(i).childMenu.get(i2);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i2) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
Menu currentParent = parentObjects.get(i);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.navdrawer_parent_item, viewGroup,false);
}
ImageView imageViewIndicator = (ImageView) view.findViewById(R.id.imageViewNav);
if (getChildrenCount(i) == 0)
imageViewIndicator.setVisibility(View.GONE);
else
imageViewIndicator.setVisibility(View.VISIBLE);
TextView textViewNavMenuName = (TextView) view.findViewById(R.id.textViewNavParentMenuName);
ImageView imageViewIcon = (ImageView) view.findViewById(R.id.imageViewIcon);
String base64 = currentParent.getImage();
if (base64 != null && !base64.equals("")) {
byte[] imageAsBytes = Base64.decode(currentParent.getImage().getBytes(), Base64
.DEFAULT);
imageViewIcon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
} else
imageViewIcon.setImageResource(R.drawable.ic_action_android);
textViewNavMenuName.setText(currentParent.getMenuName());
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean b, View view,
ViewGroup viewGroup) {
Menu currentChild = getGroup(groupPosition);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.navdrawer_child_item, viewGroup,false);
}
View divider = view.findViewById(R.id.divider);
if (b)
divider.setVisibility(View.VISIBLE);
else
divider.setVisibility(View.GONE);
TextView textViewNavMenuName = (TextView) view.findViewById(R.id.textViewNavChildMenuName);
textViewNavMenuName.setText(currentChild.childMenu.get(childPosition).getMenuName());
return view;
}
#Override
public boolean isChildSelectable(int i, int i2) {
return true;
}
}
and the model for the expandable listView like
public class Menu {
private int AssociatedApp;
private String MenuName;
private String NavigateURL;
private String ActivityName;
private String Image;
private int MenuID;
public ArrayList<ChildMenu> childMenu;
public ArrayList<ChildMenu> getChildMenu() {
return childMenu;
}
public void setChildMenu(ArrayList<ChildMenu> childMenu) {
this.childMenu = childMenu;
}
public int getAssociatedApp() {
return AssociatedApp;
}
public void setAssociatedApp(int associatedApp) {
AssociatedApp = associatedApp;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public String getNavigateURL() {
return NavigateURL;
}
public void setNavigateURL(String navigateURL) {
NavigateURL = navigateURL;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public Menu() {
}
public int getMenuID() {
return MenuID;
}
public class ChildMenu {
private int AssociatedApp;
private String MenuName;
private String NavigateURL;
private String ActivityName;
private String Image;
private int MenuID;
public ChildMenu(String menuName, String activityName) {
this.MenuName = menuName;
this.ActivityName=activityName;
}
public ChildMenu() {
}
public int getAssociatedApp() {
return AssociatedApp;
}
public void setAssociatedApp(int associatedApp) {
AssociatedApp = associatedApp;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public String getNavigateURL() {
return NavigateURL;
}
public void setNavigateURL(String navigateURL) {
NavigateURL = navigateURL;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public int getMenuID() {
return MenuID;
}
}
}
ok now you can create your menu with data and bindwith expandable listview
elv = (ExpandableListView)findViewById(R.id.elv);
elv.setOnGroupExpandListener(onGroupExpandListenser);
MyExpandableAdapter adapter = new MyExpandableAdapter(this, getData());//where getData() will return list of data.
elv.setAdapter(adapter);
parent xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="12dp"
android:paddingLeft="12dp"
android:paddingTop="12dp">
<ImageView
android:contentDescription="#string/app_name"
android:id="#+id/imageViewIcon"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentLeft="true"
android:layout_margin="4dp"
/>
<TextView
android:id="#+id/textViewNavParentMenuName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/imageViewNav"
android:layout_toRightOf="#+id/imageViewIcon"
android:padding="10dp"
android:textSize="15sp"/>
<ImageView
android:contentDescription="#string/app_name"
android:id="#+id/imageViewNav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="4dp"
android:src="#drawable/ic_action_more_nav"
/>
</RelativeLayout>
<include
layout="#layout/divider"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
child 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:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/textViewNavChildMenuName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="45dp"
android:gravity="center_vertical"
android:text="TextView"
android:padding="16dp"/>
<include
layout="#layout/divider"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
adding listener for expandable listView like this. groupExpandlistener is used for collasping other groups while open one
private int lastExpandedPosition = -1;
for setting up listener
elv.setOnChildClickListener(new DrawerItemClickListener());
elv.setOnGroupClickListener(new DrawerItemClickListener());
elv.setOnGroupExpandListener(new DrawerItemClickListener());
private class DrawerItemClickListener implements ExpandableListView.OnChildClickListener,
ExpandableListView.OnGroupClickListener, ExpandableListView.OnGroupExpandListener {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int
childPosition, long id) {
selectItem(childPosition, navigationConfig.getBaseExpandableListAdapter
().getChild
(groupPosition, childPosition));
return true;
}
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
selectItem(groupPosition, navigationConfig.getBaseExpandableListAdapter
().getGroup
(groupPosition));
return false;
}
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
}
for sample data use to bind with getData(). note create constructor in model class as given in getData()
//Sample data for expandable list view.
public List<Menu> getData()
{
List<Menu> parentObjects = new ArrayList<Menu>();
for (int i = 0; i<20; i++)
{
parentObjects.add(new Menu("Mother " +i, "Father " +i, "Header " + i, "Footer " +i, getChildren(i)));
}
return parentObjects;
}
private List<Menu.ChildMenu> getChildren(int childCount)
{
List<Menu.ChildMenu> childObjects = new ArrayList<Menu.ChildMenu>();
for (int i =0; i<childCount; i++)
{
childObjects.add(new Menu.ChildMenu("Child " + (i+1), 10 +i ));
}
return childObjects;
}
I implemented a simple listview with an option to select each time only one item from it, this functionality is working properly.
Also I have a button for sorting the records in Asc or Desc order, when I am selecting a record and after that I am sorting the records the selector of the old record remains in the same old position, even when the selected position is updated different position.
MainActivity:
public class MainActivity extends Activity
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("abc", "defg", 1));
_data.add(new Person("aaa", "defg", 12));
_data.add(new Person("ccc", "defg", 13));
_data.add(new Person("bb", "defg", 14));
_data.add(new Person("aa", "defg", 144));
_data.add(new Person("fff", "defg", 199));
_adapter = new PersonAdapter(this, _data);
_listView.setAdapter(_adapter);
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
});
}
public static class Person
{
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String fName, String lName, int age)
{
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
}
listView adapter
public class PersonAdapter extends BaseAdapter
{
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
}
}
item layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_layout"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#drawable/list_selector"
android:weightSum="3" >
<TextView
android:id="#+id/f_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:id="#+id/l_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:id="#+id/age"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
I tried already to use clearChoices but after sorting I do not see the selector at all, also I tried to change the choise mode from single mode to none and then again single but without any success.
It is because you are switching the contents of the items inside the list item, but the click is bound to the position withing the ListView, therefore it doesn't "update" to the new position of the item.
I suggest you to programatically click on the new item when you finish the sorting.
Get the ID of the clicked item
public int getItemPosition(long id)
{
for (int position=0; position<mList.size(); position++)
if (mList.get(position).getId() == id)
return position;
return 0;
}
then after the sorting do the click
mList.performItemClick(
mList.getAdapter().getView(mActivePosition, null, null),
mActivePosition,
mList.getAdapter().getItemId(mActivePosition));
hope it helps!
I suggest to store the id of the selected item when it is selected, and after order the dataset, search for that id and re-select it.
I want to add edittext on list item on button click of that particular list item. I need to get texts in the edittexts. I have posted the code I managed to come up with. But when I scroll the listview the edittexts get added to other list items as well. Pls help...
MainActivity:
ArrayList<EdittextValues> etValues = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ListItemModel> arrayList = new ArrayList<>();
arrayList.add(new ListItemModel("Title 1"));
arrayList.add(new ListItemModel("Title 2"));
arrayList.add(new ListItemModel("Title 3"));
arrayList.add(new ListItemModel("Title 4"));
arrayList.add(new ListItemModel("Title 5"));
arrayList.add(new ListItemModel("Title 6"));
arrayList.add(new ListItemModel("Title 7"));
arrayList.add(new ListItemModel("Title 8"));
arrayList.add(new ListItemModel("Title 9"));
arrayList.add(new ListItemModel("Title 10"));
ListView lv = (ListView)findViewById(R.id.listview);
lv.setItemsCanFocus(true);
final CustomListAdapter adapter = new CustomListAdapter(MainActivity.this, arrayList, etValues);
lv.setAdapter(adapter);
Button btn = (Button)findViewById(R.id.show);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String all="";
for (int i=0; i<etValues.size(); i++){
all += etValues.get(i).getValue()+"\n";
}
Toast.makeText(MainActivity.this, all, Toast.LENGTH_LONG).show();
}
});
}
CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
ArrayList<ListItemModel> items;
ViewHolder holder;
Context mContext;
ArrayList<EdittextValues> etValues;
int i = 0;
public CustomListAdapter(Context context, ArrayList<ListItemModel> items, ArrayList<EdittextValues> etValues) {
this.mContext = context;
this.items = items;
this.etValues = etValues;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_row, null);
holder.tvTitle = (TextView) convertView.findViewById(R.id.title);
holder.btnAdd = (Button) convertView.findViewById(R.id.addEdittext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvTitle.setText(items.get(position).getTitle());
final View finalConvertView = convertView;
holder.btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
etValues.add(new EdittextValues(position, i, ""));
LinearLayout mLayout = (LinearLayout) finalConvertView.findViewById(R.id.llChild);
LinearLayout.LayoutParams mparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
final EditText myEditText = new EditText(mContext);
mparams.setMargins(46, 3, 46, 3);
myEditText.setLayoutParams(mparams);
mLayout.setOrientation(LinearLayout.VERTICAL);
myEditText.setPadding(10, 10, 10, 10);
myEditText.setSingleLine(true);
myEditText.setId(i);
myEditText.setHeight(72);
myEditText.setTextSize(15);
myEditText.setFocusableInTouchMode(true);
myEditText.setFocusable(true);
myEditText.setHint("Type");
mLayout.addView(myEditText);
myEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
etValues.get(myEditText.getId()).setValue(charSequence+"");
Toast.makeText(mContext, etValues.get(myEditText.getId()).getValue(), Toast.LENGTH_SHORT).show();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
i++;
}
});
return convertView;
}
private class ViewHolder {
public TextView tvTitle;
public Button btnAdd;
}
}
ListItemModel:
public class ListItemModel {
String title;
public ListItemModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
EdittextValues:
public class EdittextValues {
int ids, etIds;
String value;
public EdittextValues(int ids, int etIds, String value) {
this.ids = ids;
this.etIds = etIds;
this.value = value;
}
public int getIds() {
return ids;
}
public void setIds(int ids) {
this.ids = ids;
}
public int getEtIds() {
return etIds;
}
public void setEtIds(int etIds) {
this.etIds = etIds;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Values"/>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/show"
android:descendantFocusability="beforeDescendants"/>
</RelativeLayout>
list_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:textSize="20dp" />
<Button
android:id="#+id/addEdittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_alignTop="#+id/title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<LinearLayout
android:id="#+id/llChild"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addEdittext">
</LinearLayout>
</RelativeLayout>
You can solve this problem by using ExpandableListView. You can solve this problem by the reference of this link.
I've made a custom adapter for a ListView in order to display a String and an ImageButton within the same row. A row is generated every time the add button is clicked. The string is taken from the EditText field, while the ImageButton bin_button is allocated dinamically. Everything works fine except I can't make the bin_buttons fire an OnClick event.
I've tried several solutions. Here bin_button_listener is generated outside the add_button OnClickListener and then set. I've also tried to set listeners with a new OnClickListener every time a new bin_button was created.
Here some code:
Row layout list_string_button_layout.xml:
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
android:paddingEnd="0dp"
android:paddingTop="8dp"
android:textSize="18sp"
android:textStyle="bold"/>
<ImageButton
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingEnd="5dp"
android:background="#00ffffff"
android:src="#drawable/ic_delete_black_18dp"
android:layout_alignBottom="#+id/list_item_string"
android:layout_alignParentEnd="true"
android:focusableInTouchMode="true"
/>
</RelativeLayout>
Activity layout activity_search.xml:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ingredient_text_input"
android:hint="#string/start_typing_ingredient"
android:layout_marginTop="52dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<Button
style="#style/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_button"
android:backgroundTint="#color/colorPrimaryLight"
android:id="#+id/add_button"
android:layout_alignTop="#+id/ingredient_text_input"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ingredients_view"
android:layout_above="#+id/search_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/add_button" />
</RelativeLayout>
Custom Adapter IngredientBinAdapter:
public class IngredientBinAdapter extends BaseAdapter {
private Context context = null;
private List<HashMap<String,ImageButton>> items = new ArrayList<>();
public IngredientBinAdapter(Context context, ArrayList<HashMap<String,ImageButton>> items){
this.context=context;
this.items=items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = LayoutInflater.from(context).inflate(R.layout.list_string_button_layout,null);
HashMap<String,ImageButton> item = (HashMap<String,ImageButton>) getItem(position);
TextView string = (TextView) convertView.findViewById(R.id.list_item_string);
String key=(String) item.keySet().toArray()[0];
string.setText(key);
item.get(key).setImageResource(R.drawable.ic_delete_black_18dp);
return convertView;
}
}
Activity:
public class SearchActivity extends AppCompatActivity{
//getting resources and allocating variables
Button add_button = null;
Button search_button = null;
EditText insert_ingredient = null;
ListView ingredient_list_view = null;
ArrayList<HashMap<String,ImageButton>> ingredient_list = new ArrayList<>();
IngredientBinAdapter list_adapter = new IngredientBinAdapter(this,ingredient_list);
ArrayList<String> ingredients_utils = new ArrayList<>();
View.OnClickListener bin_button_listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("BIN_BUTTON CLICKED");
ImageButton clicked_button = (ImageButton) v;
for(Iterator<HashMap<String,ImageButton>> i = ingredient_list.iterator(); i.hasNext(); ){
HashMap<String,ImageButton> temp= i.next();
if(temp.values().toArray()[0].equals(clicked_button))
ingredient_list.remove(temp);
}
list_adapter.notifyDataSetChanged();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
}
#Override
protected void onStart(){
super.onStart();
add_button = (Button) findViewById(R.id.add_button);
search_button = (Button) findViewById(R.id.search_button2);
insert_ingredient = (EditText) findViewById(R.id.ingredient_text_input);
ingredient_list_view = (ListView) findViewById(R.id.ingredients_view);
ingredient_list_view.setAdapter(list_adapter);
//add_button listener
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String current_ingredient_string = insert_ingredient.getText().toString().trim();
if (!current_ingredient_string.isEmpty() && !ingredients_utils.contains(current_ingredient_string)) {
HashMap<String, ImageButton> temp = new HashMap<String, ImageButton>();
ImageButton temp_bin_button = new ImageButton(SearchActivity.this);
temp_bin_button.setOnClickListener(bin_button_listener);
temp.put(current_ingredient_string, temp_bin_button);
ingredient_list.add(temp);
list_adapter.notifyDataSetChanged();
}
ingredients_utils.add(insert_ingredient.getText().toString().trim());
insert_ingredient.getText().clear();
}
});
}
}
first of all
u should move your logic to onCreate() see: Difference between onCreate() and onStart()?
second
u should in your method in adapter :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. inflate view
// 2. find button
// 3. assign here listener to bin button
// i advice to use convert view pattern
}
some hints :
create data object describing row item
public class BinRow {
private String _someString;
private Drawable _imageDrawable; // (or resource id name)
public String getString() {
return _someString;
}
public Drawable getImage() {
return _imageDrawable;
}
public BinRow(String someText, Drawable imageDrawable) {
_someText = someText;
_imageDrawable = imageDrawable;
}
}
here u have adapter example ( u need adjust Album - to your BinRow & layout for row & convert view items in view holder ) - this should show you idea how adapter works :
public class AlbumAdapter extends BaseAdapter implements IListAdapter<Album> {
private List<Album> _albums;
private Context _context;
private LayoutInflater _layoutInflater;
static class ViewHolder {
ImageView imageView;
TextView albumName;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.image);
albumName = (TextView) v.findViewById(R.id.tvAlbumName);
}
}
public AlbumAdapter(List<Album> albums) {
if(albums == null) {
_albums = new ArrasyList<>();
} else {
_albums = albums;
}
}
#Override
public int getCount() {
return _albums.size();
}
#Override
public Album getItem(int position) {
return _albums.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final Album album = getItem(position);
if (_context == null) {
_context = parent.getContext();
}
if (_layoutInflater == null) {
_layoutInflater = LayoutInflater.from(_context);
}
View _view = convertView;
ViewHolder viewHolder;
if (_view == null) {
_view = _layoutInflater.inflate(R.layout.album_item_layout, parent, false);
viewHolder = new ViewHolder(_view);
_view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _view.getTag();
}
viewHolder.albumName.setText(album.getAlbumDescription());
// here u can set: image to image view & listener to image
// image view could be a button
viewHolder.imageView.setOnClickListener(View.OnClickListener);
return _view;
}
#Override
public void add(Album listElement) {
_albums.add(listElement);
}
#Override
public void addAll(List<Album> listOfElements) {
_albums.addAll(listOfElements);
}
#Override
public void clear() {
_albums.clear();
}
#Override
public void remove(Album listElement) {
_albums.remove(listElement);
}
}
public interface IListAdapter<T> {
void add(T listElement);
void addAll(List<T> listOfElements);
void clear();
void remove(T listElement);
}
above interface serves as helper for adapter list methods
I have followed this example tutorial and developed a sample application http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/
If i click on Core i want to load one more list in the same Screen under Core,How Could i do this?using my below code i am able to load the child list in another Screen,help?
My Code for ChildClickListener goes here:
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Log.d("onChildClick", "onChildClick");
String position = (String) parentItems.get(groupPosition);
Log.d("position", position);
String child = listDataChild.get(position).get(childPosition);
Log.d("child", child);
if (child.equalsIgnoreCase("Core")) {
ArrayList<String> parentItems = new ArrayList<String>();
HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>();
ArrayList<String> childItems = new ArrayList<String>();
childItems.add("corejava");
childItems.add("corejava");
childItems.add("corejava");
childItems.add("corejava");
parentItems.add(position);
listDataChild.put(parentItems.get(0), childItems);
expandableList = (ExpandableListView) findViewById(R.id.lvExp);
CoreAdapter adapter = new CoreAdapter(parentItems,
listDataChild);
CustExpListview SecondLevelexplv = new CustExpListview(
MainActivity.this);
adapter.setInflater(
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE),
MainActivity.this);
SecondLevelexplv.setAdapter(adapter);
SecondLevelexplv.setGroupIndicator(null);
expandableList.setAdapter(adapter);
}
i write one treeView adapter for you, you can use this and put many level as you want, for that you need just copy following code:
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add data for test on one list<AccountHierarchical>
AccountHierarchical obj = new AccountHierarchical();
obj.setLevelId(1);
obj.setTitle("level 1");
AccountHierarchical obj2 = new AccountHierarchical();
obj2.setLevelId(1);
obj2.setTitle("level 2");
AccountHierarchical obj3 = new AccountHierarchical();
obj3.setLevelId(1);
obj3.setTitle("level 3");
List<AccountHierarchical> emptyList = new ArrayList<AccountHierarchical>();
obj3.setList(emptyList);
List<AccountHierarchical> list2 = new ArrayList<AccountHierarchical>();
list2.add(obj3);list2.add(obj3);list2.add(obj3);list2.add(obj3);list2.add(obj3);
obj2.setList(list2);
List<AccountHierarchical> list = new ArrayList<AccountHierarchical>();
list.add(obj2);list.add(obj2);list.add(obj2);list.add(obj2);list.add(obj2);
obj.setList(list);
List<AccountHierarchical> result = new ArrayList<AccountHierarchical>();
result.add(obj);result.add(obj);result.add(obj);result.add(obj);
// create Adapter
TreeView adapter = new TreeView(result, this,
getLayoutInflater() , false, 0);
ExpandableListView expandList = (ExpandableListView)findViewById(R.id.expandableList_tree);
expandList.setGroupIndicator(null);
expandList.setAdapter(adapter);
}
CustExpListview:
public class CustExpListview extends ExpandableListView {
int intGroupPosition, intChildPosition, intGroupid;
public CustExpListview(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// widthMeasureSpec = MeasureSpec.makeMeasureSpec(400,
// MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(600,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
AccountHierarchical:
public class AccountHierarchical {
List<AccountHierarchical> list;
private String Title;
private int Id;
public int getId() {
return Id;
}
public void setLevelId(int Id) {
this.Id = Id;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public List<AccountHierarchical> getList() {
return list;
}
public void setList(List<AccountHierarchical> list) {
this.list = list;
}
}
TreeView:
public class TreeView extends BaseExpandableListAdapter implements
OnClickListener {
List<AccountHierarchical> list;
LayoutInflater inflatter;
static Context context;
boolean checkGroup;
int position;
static ProgressDialog ProgressDialog;
public TreeView( List<AccountHierarchical> list, Context context,
LayoutInflater inflatter, boolean checkGroup, int position
) {
this.list = list;
TreeView.context = context;
this.inflatter = inflatter;
this.checkGroup = checkGroup; // this is true when you call from inner.
this.position = position;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return list.get(groupPosition).getList().get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return list.get(groupPosition).getList().get(childPosition).getId();
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (checkGroup)
groupPosition = position;
List<AccountHierarchical> childtemp = list.get(groupPosition)
.getList();
// call this adapter again for creating another level
if (childtemp.get(childPosition).getList().size() > 0) {
CustExpListview SecondLevelexplv = new CustExpListview(context);
TreeView adapter = null;
adapter = new TreeView(childtemp, context,
inflatter, true, childPosition);
SecondLevelexplv.setGroupIndicator(null);
SecondLevelexplv.setAdapter(adapter);
return SecondLevelexplv;
}
// call one layout, this is last child
else {
convertView = inflatter.inflate(R.layout.grouprow, null);
TextView tv = (TextView) convertView.findViewById(R.id.grouprow);
tv.setText(list.get(groupPosition).getList().get(childPosition)
.getTitle());
tv.setPadding(0, 0, 20, 0);
convertView.setTag(list.get(groupPosition).getList()
.get(childPosition) );
convertView.setId(position);
convertView.setOnClickListener(this);
return convertView;
}
}
#Override
public int getChildrenCount(int groupPosition) {
return list.get(groupPosition).getList().size();
}
#Override
public Object getGroup(int groupPosition) {
return list.get(groupPosition);
}
#Override
public int getGroupCount() {
if (checkGroup)
return 1;
return list.size();
}
#Override
public long getGroupId(int groupPosition) {
return list.get(groupPosition).getId();
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflatter.inflate(R.layout.grouprow, null);
TextView tv = (TextView) convertView.findViewById(R.id.grouprow);
if (checkGroup)
tv.setText(list.get(position).getTitle());
else
tv.setText(list.get(groupPosition).getTitle());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
#Override
public void onClick(View v) {
// your onClick method
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ExpandableListView
android:id="#+id/expandableList_tree"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ExpandableListView>
</RelativeLayout>
grouprow.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/grouprow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text=""/>
</RelativeLayout>
snap:
You have to create a layout in the xml file (from where your core textview comes from) and display an image view below
onClick of that imageView you will just have to make your layout Gone and Visible
I have just given you direction rest relies on your skill :)
<RelativeLayout
android:id="#+id/option"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:gravity="center"
android:orientation="horizontal" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/navigationIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/nn" />
<ImageView
android:id="#+id/callOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/phonee" />
<ImageView
android:id="#+id/imageViewfeedback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/editer" />
</RelativeLayout>
In Jave File
linear.setVisibility(View.GONE);
option.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if(count==0)
{
linear.setVisibility(View.VISIBLE);
count=1;
}
else
{
linear.setVisibility(View.GONE);
count=0;
}
}
});
You need to switch to Three-Level of Expandable ListView which contains the subchild inside child.
Also check out ExpandableListView with 3 Childs