Disclaimer! The code is working fine but it isn't efficient. The problem is that I have to click the FAB TWICE before the row is added to the list view. I want to be able to click the FAB just once so the row is added to the list view!
ListItems.java
public class ListItems {
int icon;
String name;
String detail;
public ListItems(int icon,String name,String detail){
super();
this.icon = icon;
this.name = name;
this.detail = detail;
}
public String getTitle() {
return name;
}
public String getDescription() {
return detail;
}
public int getIcon() {
return icon;
}
}
............Adapter........
ListItemHelper.java
public class ListItemHelper extends ArrayAdapter<ListItems> {
private final Context context;
private final ArrayList<ListItems> itemsArrayList;
public ListItemHelper(Context context, ArrayList<ListItems> itemsArrayList) {
super(context, R.layout.list_item, itemsArrayList);
this.context = context;
this.itemsArrayList = itemsArrayList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_item, parent, false);
ImageView iconView = (ImageView) rowView.findViewById(R.id.iv_list_icon);
TextView labelView = (TextView) rowView.findViewById(R.id.tv_list_name);
TextView valueView = (TextView) rowView.findViewById(R.id.tv_detail_list);
labelView.setText(itemsArrayList.get(position).getTitle());
valueView.setText(itemsArrayList.get(position).getDescription());
iconView.setImageResource(itemsArrayList.get(position).getIcon());
return rowView;
}
}
And the fragment activity...
FragmentActivity.java
...
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//This is where the problem is ..I think!
fabCall = (FloatingActionButton) view.findViewById(R.id.fab_menu_call);
fabCall.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
list = (ListView) getActivity().findViewById(R.id.list);
list.setAdapter(adapter);
adapter = new ListItemHelper(getActivity(),generateData());
}
});
}
// Or may the problem is here.. I don't know!
private ArrayList<ListItems> generateData() {
ArrayList<ListItems> items = new ArrayList<ListItems>();
items.add(new ListItems(R.drawable.ic_shortcut_call,"Call","Shortcut added"));
return items;
}
...
here is the problem you are doing everything thing ok the but click in fab is first setting the adapter call and then puts the new data into an adapter try this code
fabCall.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
list = (ListView) getActivity().findViewById(R.id.list);
//first fill the adapter with updated list
adapter = new ListItemHelper(getActivity(),generateData())
// then set the adapter
list.setAdapter(adapter);
//notify change
adapter.notifyDataSetChanged();
;
}
});