I'm new to android. I have developed a calendar for my App and i want the user to be able to switch between months smoothly.
So I decided to use the ViewPager and to make it use unlimited amount of months i have implement this solution:
http://code.google.com/p/electricsleep/source/browse/trunk/src/com/androsz/electricsleepbeta/app/HistoryMonthActivity.java
Unfortunately it doesn't work for me. When I try to scroll left or right the next month to be showed comes until I scroll with the finger, but when i release my finger the earlier showed month comes again but the date on the indicator remains the right.
I post the code:
calendarView = new GridView(this);
calendarView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
calendarView.setNumColumns(7);
adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, newdatum);
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
calendarView.setTag(newdatum.toString());
viewpager = (ViewPager) this.findViewById(R.id.calviewpager);
viewpager.setAdapter(new MonthPagerAdapter());
viewpager.setOffscreenPageLimit(3);
mTitleIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
mTitleIndicator.setViewPager(viewpager, 1);
mTitleIndicator.setOnPageChangeListener(new PageListener());
}
private class PageListener implements OnPageChangeListener{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
final DateTime old0 = DateTime.parse(viewpager.getChildAt(0).getTag().toString());
final DateTime old1 = DateTime.parse(viewpager.getChildAt(1).getTag().toString());
final DateTime old2 = DateTime.parse(viewpager.getChildAt(2).getTag().toString());
if (focusedPage == 0) {
Log.d("FOCUSEDPAGE=0",newdatum.toString());
DateTime minus = new DateTime();
minus=old0.minusMonths(1);
viewpager.getChildAt(0).setTag(minus.toString());
viewpager.getChildAt(1).setTag(old2.toString());
viewpager.getChildAt(2).setTag(old1.toString());
}
else if (focusedPage == 2) {
Log.d("FOCUSEDPAGE=2",newdatum.toString());
DateTime plus = new DateTime();
plus=old2.plusMonths(1);
viewpager.getChildAt(0).setTag(old1.toString());
viewpager.getChildAt(1).setTag(old2.toString());
viewpager.getChildAt(2).setTag(plus.toString());
}
mTitleIndicator.setCurrentItem(1);
}
}
#Override
public void onPageSelected(int position) {
newdatum=DateTime.parse(viewpager.getChildAt(position).getTag().toString());
focusedPage = position;
}
}
private class MonthPagerAdapter extends PagerAdapter{
ViewPager container;
private GridView addMonthViewAt(int position, DateTime date) {
final GridView gv = new GridView(CalendarActivity.this);
gv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
gv.setNumColumns(7);
gv.setTag(date.toString());
setGridCellAdapterToDate(date, gv);
container.addView(gv, position);
return gv;
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeViewAt(position);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return 3;
}
#Override
public Object instantiateItem(View container, int pos) {
this.container = (ViewPager) container;
DateTime newdate=newdatum.plusMonths(pos-1);
Log.d("INSTATIATE",newdate.toString());
return addMonthViewAt(pos, newdate);
}
#Override
public String getPageTitle(int position) {
final GridView gv = (GridView) container.getChildAt(position);
DateTime dt=DateTime.parse(gv.getTag().toString());
String title=dt.monthOfYear().getAsText()+" "+dt.getYear();
Log.d("GET PAGE TITLE",dt.toString());
return title;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
private void setGridCellAdapterToDate(DateTime newdate, GridView gridview){
GridCellAdapter adapt = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, newdate);
adapt.notifyDataSetChanged();
gridview.setAdapter(adapt);
}
And the GridCellAdapter code:
public class GridCellAdapter extends BaseAdapter implements OnClickListener{
private final Context _context;
private final List<String> list;
private Button gridcell;
public GridCellAdapter(Context context, int textViewResourceId, DateTime datum){
super();
this._context = context;
this.list = new ArrayList<String>();
printMonth(datum);
}
public String getItem(int position){
return list.get(position);
}
public int getCount(){
return list.size();
}
private void printMonth(DateTime cal){
int daysInMonth = cal.dayOfMonth().getMaximumValue();
int daysInPrevMonth = cal.minusMonths(1).dayOfMonth().getMaximumValue()+1;
int trailingSpaces = cal.withDayOfMonth(1).dayOfWeek().get()-1;
SQLiteAdapter sql= new SQLiteAdapter(getApplicationContext());
sql.openToWrite(month(cal));
if(sql.tableExists()){
String back="blue";
for(int i=0;i<7;i++)
list.add("DAY:"+cal.withDayOfWeek(i+1).toString()+": ");
for (int i = 0; i < trailingSpaces; i++){
if(sql.rowExists(cal.minusMonths(1).withDayOfMonth((daysInPrevMonth-trailingSpaces)+i).toString("yyyy-MM-dd")))
back="green";
else back="blue";
list.add("GREY:"+cal.minusMonths(1).withDayOfMonth((daysInPrevMonth-trailingSpaces)+i).toString("yyyy-MM-dd")+": "+":"+back);
}
for (int i = 1; i <= daysInMonth; i++){
if(sql.rowExists(cal.withDayOfMonth(i).toString("yyyy-MM-dd")))
back="green";
else back="blue";
if (cal.withDayOfMonth(i).toString("yyyy-MM-dd").equals(DateTime.now().toString("yyyy-MM-dd"))){
list.add("WHITE:"+cal.withDayOfMonth(i).toString("yyyy-MM-dd")+":"+checkIsFeiertag(cal.withDayOfMonth(i)).toString()+":"+back);
}
else{
checkIsFeiertag(cal.withDayOfMonth(i));
list.add("BLUE:"+cal.withDayOfMonth(i).toString("yyyy-MM-dd")+":"+checkIsFeiertag(cal.withDayOfMonth(i)).toString()+":"+back);
}
}
for (int i = 0; i < list.size() % 7; i++){
if(sql.rowExists(cal.plusMonths(1).withDayOfMonth(i+1).toString("yyyy-MM-dd")))
back="green";
else back="blue";
list.add("GREY:"+cal.plusMonths(1).withDayOfMonth(i+1).toString("yyyy-MM-dd")+": "+":"+back);
}
}
else{
for(int i=0;i<7;i++)
list.add("DAY:"+cal.withDayOfWeek(i+1).toString()+": "+": ");
for (int i = 0; i < trailingSpaces; i++){
list.add("GREY:"+cal.minusMonths(1).withDayOfMonth((daysInPrevMonth-trailingSpaces)+i).toString("yyyy-MM-dd")+": "+": ");
}
for (int i = 1; i <= daysInMonth; i++){
if (cal.withDayOfMonth(i).toString("yyyy-MM-dd").equals(DateTime.now().toString("yyyy-MM-dd"))){
list.add("WHITE:"+cal.withDayOfMonth(i).toString("yyyy-MM-dd")+":"+checkIsFeiertag(cal.withDayOfMonth(i)).toString()+": ");
}
else{
checkIsFeiertag(cal.withDayOfMonth(i));
list.add("BLUE:"+cal.withDayOfMonth(i).toString("yyyy-MM-dd")+":"+checkIsFeiertag(cal.withDayOfMonth(i)).toString()+": ");
}
}
for (int i = 0; i < list.size() % 7; i++){
list.add("GREY:"+cal.plusMonths(1).withDayOfMonth(i+1).toString("yyyy-MM-dd")+": "+": ");
}
}
sql.close();
}
public long getItemId(int position){
return position;
}
#SuppressLint("NewApi")
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
if(row == null){
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.calendar_day_gridcell, parent, false);
}
gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
String[] day_color = list.get(position).split(":");
DateTime datum = DateTime.parse(day_color[1]);
if(!(day_color[0].equals("DAY"))){
gridcell.setText(String.valueOf(datum.getDayOfMonth()));
gridcell.setTag(datum.toString("yyyy-MM-dd"));
gridcell.setOnClickListener(this);
if (!day_color[2].equals(" "))
gridcell.setTextColor(Color.RED);
else if (day_color[0].equals("GREY"))
{
gridcell.setTextColor(Color.LTGRAY);
}
else if (day_color[0].equals("WHITE"))
{
gridcell.setTextColor(Color.WHITE);
}
else if (day_color[0].equals("BLUE"))
{
gridcell.setTextColor(getResources().getColor(R.color.static_text_color));
}
if(day_color[3].equals("green")){
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
gridcell.setBackgroundDrawable(getResources().getDrawable(R.drawable.calendar_tile_green));
} else {
gridcell.setBackground(getResources().getDrawable(R.drawable.calendar_tile_green));
}
}
}
else {
gridcell.setText(datum.toString("EE"));
gridcell.setClickable(false);
}
gridcell.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
if(gridcell.getBackground()==getResources().getDrawable(R.drawable.calendar_tile_green)){
SQLiteAdapter sql= new SQLiteAdapter(context);
DateTime bt = DateTime.parse(gridcell.getTag().toString());
sql.openToWrite(month(bt));
sql.getRows(month(bt));
sql.close();
}
return true;
}
});
return row;
}
Of course I'm accepting different solutions to provide the same smoothing scrolling.
Related
UPDATE - Added experimentation result
Is it possible to implement an ExpandableListView to have a viewpager child?
I tried to put viewpager as a child in ExpandableListView but it is not showing :( I also tried to add it under ScrollView but same result so I think it is a problem being under a scrollable view? But when I removed ScrollView it showed up. What can I do so they can go together?
This is what I am aiming for to do
And this is what happen when I tried to implement on my own code.
P.S. This is just a sampler and not yet finished. I have 3 children and my layout displayed thrice also with each item inside
can you check this API
https://developer.android.com/reference/android/widget/ExpandableListView
A view that shows items in a vertically scrolling two-level list
I made a sample in Java. Hope that helps!
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnClearChecks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Clear Checks" />
<Button
android:id="#+id/btnPutOrder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Put Order" />
</LinearLayout>
<ExpandableListView
android:id="#+id/expandedListView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ExpandableListView>
</LinearLayout>
expanded_list_group.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<CheckBox
android:id="#+id/cb_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_gravity="center_vertical" />
<TextView
android:id="#+id/tv_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"
android:textSize="30sp" />
</LinearLayout>
list_child_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="wrap_content"
android:orientation="vertical"
android:paddingStart="60dp">
<android.support.v4.view.ViewPager
android:id="#+id/layout_child"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
list_pager_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="#integer/pager_col_count"
android:rowCount="#integer/pager_row_count">
</GridLayout>
integers.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="pager_col_count">3</integer>
<integer name="pager_row_count">3</integer>
</resources>
ChildItemSample.java
public class ChildItemSample {
private boolean checked = false;
private String name;
private int qty;
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getName() {
return name;
}
public ChildItemSample(String name, int qty){
this.name = name;
this.qty = qty;
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button clearChecks, putOrder;
ExpandableListView expandableListView;
ExpandableListPagerAdapter expandableListAdapter;
int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = findViewById(R.id.expandedListView);
clearChecks = findViewById(R.id.btnClearChecks);
putOrder = findViewById(R.id.btnPutOrder);
List<String> listTitle = genGroupList();
expandableListAdapter = new ExpandableListPagerAdapter(this, getSupportFragmentManager(), listTitle, genChildList(listTitle));
expandableListView.setAdapter(expandableListAdapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if(lastExpandedPosition != -1 && (lastExpandedPosition != groupPosition)){
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
clearChecks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expandableListAdapter.clearChecks();
}
});
putOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<String> putOrder = expandableListAdapter.getOrderList();
StringBuilder msg = new StringBuilder();
for(int i=0; i<putOrder.size(); i++){
msg.append(putOrder.get(i));
msg.append("\n");
}
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<String> genGroupList(){
ArrayList<String> listGroup = new ArrayList<>();
for(int i=1; i<10; i++){
listGroup.add("Group: " + i);
}
return listGroup;
}
private Map<String, List<ChildItemSample>> genChildList(List<String> header){
Map<String, List<ChildItemSample>> listChild = new HashMap<>();
for(int i=0; i<header.size(); i++){
List<ChildItemSample> testDataList = new ArrayList<>();
int a = (int)(Math.random()*28);
for(int j=0; j<a; j++){
ChildItemSample testItem = new ChildItemSample("Child " + (j + 1), 0);
testDataList.add(testItem);
}
listChild.put(header.get(i), testDataList);
}
return listChild;
}
}
ExpandableListPagerAdapter.java:
public class ExpandableListPagerAdapter extends BaseExpandableListAdapter {
private int child_items_per_page;
private Context context;
private FragmentManager fm;
private List<String> listGroup;
private Map<String, List<ChildItemSample>> listChild;
private static int checkedBoxesCount;
private boolean[] checkedGroup;
ExpandableListPagerAdapter(Context context, FragmentManager manager, List<String> listGroup, Map<String,
List<ChildItemSample>> listChild) {
this.context = context;
fm = manager;
this.listGroup = listGroup;
this.listChild = listChild;
checkedBoxesCount = 0;
checkedGroup = new boolean[listGroup.size()];
child_items_per_page = context.getResources().getInteger(R.integer.pager_col_count) *
context.getResources().getInteger(R.integer.pager_row_count);
}
#Override
public int getGroupCount() {
return listGroup.size();
}
#Override
//******* Special *******
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public String getGroup(int groupPosition) {
return listGroup.get(groupPosition);
}
#Override
public ChildItemSample getChild(int groupPosition, int childPosition) {
return listChild.get(listGroup.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) {
String itemGroup = getGroup(groupPosition);
GroupViewHolder groupViewHolder;
if(view == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.expanded_list_group, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.tvGroup = view.findViewById(R.id.tv_group);
groupViewHolder.cbGroup = view.findViewById(R.id.cb_group);
groupViewHolder.cbGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
checkedGroup[pos] = !checkedGroup[pos];
for(ChildItemSample item : listChild.get(listGroup.get(pos))){
item.setChecked(checkedGroup[pos]);
}
notifyDataSetChanged();
}
});
view.setTag(groupViewHolder);
}else {
groupViewHolder = (GroupViewHolder)view.getTag();
}
groupViewHolder.tvGroup.setText(String.format("%s (%d)", itemGroup, listChild.get(listGroup.get(groupPosition)).size()));
if(checkedGroup[groupPosition]) groupViewHolder.cbGroup.setChecked(true);
else groupViewHolder.cbGroup.setChecked(false);
groupViewHolder.cbGroup.setTag(groupPosition);
return view;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_child_pager, null);
ViewPager childLayout = rowView.findViewById(R.id.layout_child);
List<ChildItemSample> childItemSampleList = listChild.get(listGroup.get(groupPosition));
ChildPagerAdapter adapter = new ChildPagerAdapter(fm, childItemSampleList, child_items_per_page);
childLayout.setAdapter(adapter);
return rowView;
}
public class ChildPagerAdapter extends FragmentStatePagerAdapter {
private List<ChildItemSample> pagerItemList;
private int items_per_page;
ChildPagerAdapter(FragmentManager fm, List<ChildItemSample> pagerItemList, int items_per_page) {
super(fm);
this.pagerItemList = pagerItemList;
this.items_per_page = items_per_page;
}
#Override
public Fragment getItem(int position) {
return ChildFragment.newInstance(position, pagerItemList, items_per_page);
}
#Override
public int getCount() {
int remainedItemCount = pagerItemList.size()%child_items_per_page;
if(remainedItemCount == 0)
return (pagerItemList.size()/child_items_per_page);
else
return (pagerItemList.size()/child_items_per_page + 1);
}
}
public static class ChildFragment extends Fragment {
private static final String SECTION_NUMBER = "section_number";
private static final String ITEMS_PER_PAGE = "items/page";
private static List<ChildItemSample> itemList;
public ChildFragment() {}
public static ChildFragment newInstance(int sectionNumber, List<ChildItemSample> pagerItemList,
int itemPerPage) {
ChildFragment fragment = new ChildFragment();
Bundle args = new Bundle();
args.putInt(SECTION_NUMBER, sectionNumber);
args.putInt(ITEMS_PER_PAGE, itemPerPage);
fragment.setArguments(args);
itemList = pagerItemList;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int child_items_per_page = getArguments().getInt(ITEMS_PER_PAGE);
int start_item = getArguments().getInt(SECTION_NUMBER)*child_items_per_page;
int itemCount = itemList.size() - getArguments().getInt(SECTION_NUMBER)*child_items_per_page;
if(itemCount > child_items_per_page) itemCount = child_items_per_page;
itemCount += getArguments().getInt(SECTION_NUMBER)*child_items_per_page;
GridLayout pageView = (GridLayout)inflater.inflate(R.layout.list_pager_item, container, false);
for(int i=start_item; i<itemCount; i++){
ChildItemSample expandedListText = itemList.get(i);
CheckBox cbChild = new CheckBox(getContext());
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.width = (int)(80 * getContext().getResources().getDisplayMetrics().density);
cbChild.setLayoutParams(params);
cbChild.setChecked(expandedListText.isChecked());
cbChild.setText(expandedListText.getName());
cbChild.setTag(i);
pageView.addView(cbChild);
cbChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
int pos = (int) view.getTag();
ChildItemSample selectedItem = itemList.get(pos);
selectedItem.setChecked(cb.isChecked());
if(cb.isChecked()){
checkedBoxesCount++;
Toast.makeText(getContext(),"Checked value is: " +
itemList.get(pos).getName(),
Toast.LENGTH_SHORT).show();
}else {
checkedBoxesCount--;
if(checkedBoxesCount == 0){
Toast.makeText(getContext(),"nothing checked",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getContext(),"unchecked",Toast.LENGTH_SHORT).show();
}
}
}
});
}
return pageView;
}
}
public void clearChecks() {
for(int i=0; i<checkedGroup.length; i++) checkedGroup[i] = false;
for(List<ChildItemSample> value : listChild.values()) {
for (ChildItemSample sample : value) {
sample.setChecked(false);
}
}
checkedBoxesCount = 0;
notifyDataSetChanged();
}
public ArrayList<String> getOrderList(){
ArrayList<String> overallOrder = new ArrayList<>();
for(int i=0; i<getGroupCount(); i++){
//for(int j=0; j<getChildrenCount(i); j++){
for(int j=0; j<listChild.get(getGroup(i)).size(); j++){
if(getChild(i,j).isChecked()){
String newOrder = getGroup(i) + ">" + getChild(i, j).getName();
overallOrder.add(newOrder);
}
}
}
return overallOrder;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class GroupViewHolder {
CheckBox cbGroup;
TextView tvGroup;
}
}
Another sample adapter that has ViewPager child (Without fragment)
public class ExpandableListPagerAdapter2 extends BaseExpandableListAdapter {
private Context context;
private List<String> listGroup;
private Map<String, List<ChildItemSample>> listChild;
private int checkedBoxesCount;
private boolean[] checkedGroup;
private int child_items_per_page;
ExpandableListPagerAdapter2(Context context, List<String> listGroup, Map<String,
List<ChildItemSample>> listChild) {
this.context = context;
this.listGroup = listGroup;
this.listChild = listChild;
checkedBoxesCount = 0;
checkedGroup = new boolean[listGroup.size()];
child_items_per_page = context.getResources().getInteger(R.integer.pager_col_count) *
context.getResources().getInteger(R.integer.pager_row_count);
}
#Override
public int getGroupCount() {
return listGroup.size();
}
// ******* Special *******
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public String getGroup(int groupPosition) {
return listGroup.get(groupPosition);
}
#Override
public ChildItemSample getChild(int groupPosition, int childPosition) {
return listChild.get(listGroup.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) {
String itemGroup = getGroup(groupPosition);
GroupViewHolder groupViewHolder;
if(view == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.expanded_list_group, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.tvGroup = view.findViewById(R.id.tv_group);
groupViewHolder.cbGroup = view.findViewById(R.id.cb_group);
groupViewHolder.cbGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
checkedGroup[pos] = !checkedGroup[pos];
for(ChildItemSample item : listChild.get(listGroup.get(pos))){
item.setChecked(checkedGroup[pos]);
}
notifyDataSetChanged();
}
});
view.setTag(groupViewHolder);
}else {
groupViewHolder = (GroupViewHolder)view.getTag();
}
groupViewHolder.tvGroup.setText(String.format("%s (%d)", itemGroup, listChild.get(listGroup.get(groupPosition)).size()));
if(checkedGroup[groupPosition]) groupViewHolder.cbGroup.setChecked(true);
else groupViewHolder.cbGroup.setChecked(false);
groupViewHolder.cbGroup.setTag(groupPosition);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_child_pager, null);
ViewPager childLayout = rowView.findViewById(R.id.layout_child);
List<ChildItemSample> childItemSampleList = listChild.get(listGroup.get(groupPosition));
ChildPagerAdapter adapter = new ChildPagerAdapter(childItemSampleList);
childLayout.setAdapter(adapter);
return rowView;
}
public class ChildPagerAdapter extends PagerAdapter {
private List<ChildItemSample> pagerItemList;
ChildPagerAdapter(List<ChildItemSample> pagerItemList) {
this.pagerItemList = pagerItemList;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
int start_item = position*child_items_per_page;
int itemCount = pagerItemList.size() - start_item;
if(itemCount > child_items_per_page) itemCount = child_items_per_page;
itemCount += start_item;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
GridLayout pageView = (GridLayout)inflater.inflate(R.layout.list_pager_item, container, false);
for(int i=start_item; i<itemCount; i++){
ChildItemSample expandedListText = pagerItemList.get(i);
CheckBox cbChild = new CheckBox(context);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.width = (int)(80 * context.getResources().getDisplayMetrics().density);
cbChild.setLayoutParams(params);
cbChild.setChecked(expandedListText.isChecked());
cbChild.setText(expandedListText.getName() + "(" + expandedListText.getQty() + ")");
cbChild.setTag(i);
pageView.addView(cbChild);
cbChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int) view.getTag();
final ChildItemSample selectedItem = pagerItemList.get(pos);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(selectedItem.getName());
final EditText editText = new EditText(context);
editText.setText("");
editText.append(String.valueOf(selectedItem.getQty()));
builder.setView(editText);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
selectedItem.setQty(Integer.parseInt(editText.getText().toString()));
ExpandableListPagerAdapter2.this.notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", null);;
builder.show();
editText.requestFocus();
editText.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager keyboard = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(editText, 0);
}
},200);
}
});
}
container.addView(pageView);
return pageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
int remainedItemCount = pagerItemList.size()%child_items_per_page;
if(remainedItemCount == 0)
return (pagerItemList.size()/child_items_per_page);
else
return (pagerItemList.size()/child_items_per_page + 1);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
public void clearChecks() {
for(int i=0; i<checkedGroup.length; i++) checkedGroup[i] = false;
for(List<ChildItemSample> value : listChild.values()) {
for (ChildItemSample sample : value) {
sample.setChecked(false);
}
}
checkedBoxesCount = 0;
notifyDataSetChanged();
}
public ArrayList<ChildItemSample> getOrderList(){
ArrayList<ChildItemSample> overallOrder = new ArrayList<>();
for(int i=0; i<getGroupCount(); i++){
for(int j=0; j<listChild.get(getGroup(i)).size(); j++){
if(getChild(i,j).getQty() > 0){
ChildItemSample newOrder = new ChildItemSample(getGroup(i) + ">" +
getChild(i, j).getName(), getChild(i, j).getQty());
overallOrder.add(newOrder);
}
}
}
return overallOrder;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class GroupViewHolder {
CheckBox cbGroup;
TextView tvGroup;
}
}
There's a system visual effect everytime you click a view in Android. In Lollipop it's the ripple effect. When I created a ListView and associated it to an ordinary ArrayAdapter, this effect was present. Now that I've added a custom ListView, this effect is lost.
Now, I've tried to isolate what the problem is, and since using the same list item layout with a default adapter worked nicely, I would say that the problem is on my custom adapter.
I've seen many solutions related to this case that just implemented the ripple effect calling some drawables; this is not what I'm trying to do. The ripple effect shows only because I'm running the app on Android 5, now what I want to do is to have the default system highlight effect for my items when they're being clicked.
Here are the (hopefully) related pieces of my custom adapter:
public class CustomCardSetsAdapter extends BaseAdapter {
List<Card> totalList;
ArrayList<Boolean> hiddenItems;
ListView parentLV;
Integer curPosition = -1;
public static int selectedRowIndex;
public CustomCardSetsAdapter(CardSets cardList, ListView parentListView)
{
this.parentLV = parentListView;
assignSetValues(cardList);
totalList = cardList.getBlackrockMountain();
totalList.addAll(cardList.getClassic());
totalList.addAll(cardList.getCurseofNaxxramas());
totalList.addAll(cardList.getGoblinsvsGnomes());
Collections.sort(totalList,
new Comparator<Card>() {
public int compare(Card f1, Card f2) {
return f1.toString().compareTo(f2.toString());
}
});
hiddenItems = new ArrayList<>();
for (int i = 0; i < totalList.size(); i++) {
if(!totalList.get(i).getCollectible())
hiddenItems.add(true);
else
hiddenItems.add(false);
}
}
#Override
public int getCount() {
return (totalList.size() - getHiddenCount());
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final int index = getRealPosition(position);
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.card_list_item, parentLV, false);
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer prevPosition = curPosition;
curPosition = position;
if(prevPosition >= parentLV.getFirstVisiblePosition() &&
prevPosition <= parentLV.getLastVisiblePosition())
{
View view = parentLV.getChildAt(prevPosition- parentLV.getFirstVisiblePosition());
parentLV.getAdapter().getView(prevPosition,view, parentLV);
}
v.setBackgroundColor(Color.WHITE);
}
});
Card curCard = totalList.get(index);
TextView cardName = (TextView) convertView.findViewById(R.id.cardName);
cardName.setText(curCard.getName());
setRarityColor(curCard,cardName);
TextView manaCost = (TextView) convertView.findViewById(R.id.manaCost);
manaCost.setText((curCard.getCost()).toString());
ImageView setIcon = (ImageView) convertView.findViewById(R.id.setIcon);
setSetIcon(curCard,setIcon);
if(position == curPosition)
convertView.setBackgroundColor(Color.WHITE);
else
convertView.setBackgroundColor(Color.TRANSPARENT);
return convertView;
}
#Override
public int getItemViewType(int position) {
return R.layout.card_list_item;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public boolean isEmpty() {
return false;
}
private int getHiddenCount()
{
int count = 0;
for(int i = 0;i <totalList.size();i++)
if(hiddenItems.get(i))
count++;
return count;
}
private int getRealPosition(int position) {
int hElements = getHiddenCountUpTo(position);
int diff = 0;
for(int i=0;i<hElements;i++) {
diff++;
if(hiddenItems.get(position+diff))
i--;
}
return (position + diff);
}
private int getHiddenCountUpTo(int location) {
int count = 0;
for(int i=0;i<=location;i++) {
if(hiddenItems.get(i))
count++;
}
return count;
}
}
Thanks in advance.
in your ListView XML, add:
android:drawSelectorOnTop="true"
I also think you are using your adapter wrong...
Use the ViewHolder Pattern on your Adapter:
public class CustomCardSetsAdapter extends BaseAdapter {
List<Card> totalList;
ArrayList<Boolean> hiddenItems;
ListView parentLV;
Integer curPosition = -1;
public static int selectedRowIndex;
private class ViewHolderRow{
TextView cardName;
TextView manaCost;
ImageView setIcon;
}
public CustomCardSetsAdapter(CardSets cardList, ListView parentListView)
{
this.parentLV = parentListView;
assignSetValues(cardList);
totalList = cardList.getBlackrockMountain();
totalList.addAll(cardList.getClassic());
totalList.addAll(cardList.getCurseofNaxxramas());
totalList.addAll(cardList.getGoblinsvsGnomes());
Collections.sort(totalList,
new Comparator<Card>() {
public int compare(Card f1, Card f2) {
return f1.toString().compareTo(f2.toString());
}
});
hiddenItems = new ArrayList<>();
for (int i = 0; i < totalList.size(); i++) {
if(!totalList.get(i).getCollectible())
hiddenItems.add(true);
else
hiddenItems.add(false);
}
}
#Override
public int getCount() {
return (totalList.size() - getHiddenCount());
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final int index = getRealPosition(position);
ViewHolderRow theRow;
if(convertView == null) {
theRow = new ViewHolderRow();
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.card_list_item, parentLV, false);
// Cache your views
theRow.cardName = (TextView) convertView.findViewById(R.id.cardName);
theRow.manaCost = (TextView) convertView.findViewById(R.id.manaCost);
theRow.setIcon = (ImageView) convertView.findViewById(R.id.setIcon);
// Set the Tag to the ViewHolderRow
convertView.setTag(theRow);
}else{
// get the Row to re-use
theRow = (ViewHolderRow) convertView.getTag();
}
//... Removed convertView.setOnClickListener
Card curCard = totalList.get(index);
// Set Items
theRow.cardName.setText(curCard.getName());
setRarityColor(curCard,theRow.cardName);
theRow.manaCost.setText((curCard.getCost()).toString());
setSetIcon(curCard,theRow.setIcon);
if(position == curPosition){
convertView.setBackgroundColor(Color.WHITE);
}else{
convertView.setBackgroundColor(Color.TRANSPARENT);
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return R.layout.card_list_item;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public boolean isEmpty() {
return false;
}
private int getHiddenCount()
{
int count = 0;
for(int i = 0;i <totalList.size();i++)
if(hiddenItems.get(i))
count++;
return count;
}
private int getRealPosition(int position) {
int hElements = getHiddenCountUpTo(position);
int diff = 0;
for(int i=0;i<hElements;i++) {
diff++;
if(hiddenItems.get(position+diff))
i--;
}
return (position + diff);
}
private int getHiddenCountUpTo(int location) {
int count = 0;
for(int i=0;i<=location;i++) {
if(hiddenItems.get(i))
count++;
}
return count;
}
}
Set an onListItemClickListener instead of using this on the entire convertView...
yourListView.setOnItemClickListener(ListListener);
private final OnItemClickListener ListListener = new OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
// ... Do something on click
}
}
I have a ListView, and I want to implement fastscroll with SectionIndexer with 3 item ImageViews per row item like this:
https://www.dropbox.com/s/th83hznhqzr01ds/cap2.png?dl=0
I want implement onclicklistener for each imageview 1, 2, 3 but when I use
imageview1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO here
}
});
it doesn't work - onClickListener is not caught, I don't know why.
Here is my adapter code:
public class LazyImageLoadAdapter extends BaseAdapter implements SectionIndexer{
private Context _context;
private TopActivity _parentActivity;
private static LayoutInflater inflater=null;
public CoverBookLoader _coverBookLoader;
private ArrayList<RowBook> _arrListRowBooks;
private int sizeView;
public LazyImageLoadAdapter(Context context, ArrayList<RowBook> arrListRowBooks) {
this._context = context;
this._parentActivity = (TopActivity) context;
this.sizeView = _parentActivity.getScreenWidth();
this._arrListRowBooks = arrListRowBooks;
inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_coverBookLoader = new CoverBookLoader(_context);
}
public int getCount() {
// return data.length;
return _arrListRowBooks.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public LinearLayout llBook1;
public ImageView ivBookCover1;
public ProgressBar pbLoadingBookCover1;
public LinearLayout llBook2;
public ImageView ivBookCover2;
public ProgressBar pbLoadingBookCover2;
public LinearLayout llBook3;
public ImageView ivBookCover3;
public ProgressBar pbLoadingBookCover3;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holderBook;
LayoutParams lpSizeBook = new LayoutParams(sizeView / 3, sizeView * 3 / 5);
if(convertView==null){
vi = inflater.inflate(R.layout.listview_row, parent, false);
holderBook = new ViewHolder();
holderBook.llBook1 = (LinearLayout) vi.findViewById(R.id.llBook1);
holderBook.llBook1.setLayoutParams(lpSizeBook);
holderBook.ivBookCover1 = (ImageView) vi.findViewById(R.id.ivBookCover1);
holderBook.pbLoadingBookCover1 = (ProgressBar) vi.findViewById(R.id.pbLoadingCoverImageBook1);
holderBook.llBook2 = (LinearLayout) vi.findViewById(R.id.llBook2);
holderBook.llBook2.setLayoutParams(lpSizeBook);
holderBook.ivBookCover2 = (ImageView) vi.findViewById(R.id.ivBookCover2);
holderBook.pbLoadingBookCover2 = (ProgressBar) vi.findViewById(R.id.pbLoadingCoverImageBook2);
holderBook.llBook3 = (LinearLayout) vi.findViewById(R.id.llBook3);
holderBook.llBook3.setLayoutParams(lpSizeBook);
holderBook.ivBookCover3 = (ImageView) vi.findViewById(R.id.ivBookCover3);
holderBook.pbLoadingBookCover3 = (ProgressBar) vi.findViewById(R.id.pbLoadingCoverImageBook3);
vi.setTag( holderBook );
}
else {
holderBook=(ViewHolder)vi.getTag();
}
LinearLayout llBook1 = holderBook.llBook1;
llBook1.setLayoutParams(lpSizeBook);
ImageView ivBookCover1 = holderBook.ivBookCover1;
ProgressBar pbLoadingBookCover1 = holderBook.pbLoadingBookCover1;
LinearLayout llBook2 = holderBook.llBook2;
llBook2.setLayoutParams(lpSizeBook);
ImageView ivBookCover2 = holderBook.ivBookCover2;
ProgressBar pbLoadingBookCover2 = holderBook.pbLoadingBookCover2;
LinearLayout llBook3 = holderBook.llBook3;
llBook3.setLayoutParams(lpSizeBook);
ImageView ivBookCover3 = holderBook.ivBookCover3;
ProgressBar pbLoadingBookCover3 = holderBook.pbLoadingBookCover3;
RowBook rowBook = _arrListRowBooks.get(position);
if (rowBook.getSize() < 3) {
llBook3.setVisibility(View.VISIBLE);
}
if (rowBook.getSize() < 2) {
llBook2.setVisibility(View.VISIBLE);
}
if (rowBook != null) {
for (int i = 0; i < rowBook.getSize(); i++) {
switch (i) {
case 0:
addBook(rowBook.getBookAt(i), ivBookCover1, pbLoadingBookCover1);
break;
case 1:
addBook(rowBook.getBookAt(i), ivBookCover2, pbLoadingBookCover2);
break;
case 2:
addBook(rowBook.getBookAt(i), ivBookCover3, pbLoadingBookCover3);
break;
}
}
}
return vi;
}
private void addBook(Books book , ImageView ivBookCover, ProgressBar pbLoadingCoverImageBook){
ivBookCover.setImageResource(R.drawable.blank_book);
ivBookCover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO here
}
});
JSONObject objBookTag = new JSONObject();
try {
objBookTag.put(Define.KEY_JSONOBJ_BOOK_ID, book.getId());
objBookTag.put(Define.KEY_JSONOBJ_BOOK_URL_THUMBNAIL, book.urlThumbnail);
ivBookCover.setTag(objBookTag);
} catch (JSONException e) {
e.printStackTrace();
ivBookCover.setTag("{\""+Define.KEY_JSONOBJ_BOOK_ID+"\":\"" + book.getId()+"\", \""+Define.KEY_JSONOBJ_BOOK_URL_THUMBNAIL+"\":\""+book.urlThumbnail+"\"");
}
_coverBookLoader.DisplayImage(book.urlThumbnail, ivBookCover, book.getId(), pbLoadingCoverImageBook);
}
private String[] mSections;
public void initSection(String[] sections){
mSections = sections;
}
#Override
public Object[] getSections() {
Log.d("ListView", "Get sections");
if (mSections != null) {
String[] sectionsArr = new String[mSections.length];
for (int i=0; i < mSections.length; i++) {
sectionsArr[i] = "" + mSections[i];
}
return sectionsArr;
}
return null;
}
#Override
public int getPositionForSection(int sectionIndex) {
if (mSections != null) {
Log.d("ListView", "Get position for section");
for (int i=0; i < this.getCount(); i++) {
if (mSections[sectionIndex].equals("" + i)) {
return i;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
Log.d("ListView", "Get section");
return 0;
}
}
As my above comment reply, my adapter not fault, my fault is in my custom listview :
public class IndexableListView extends ListView {
// TODO
#Override
/**
* intercept touch event - **WRONG HERE**
*/
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
// TODO
}
And when i remove onInterceptTouchEvent, my problem is resolved
I have ArrayList and I want to sort and group all data by header in Android.
How it is possible in Android? please help me.below me from owner And set header Me And Joe Manager From owner And set Header in listview. How to do that in Android?
My code in below::
public class Request extends Activity {
private String assosiatetoken;
private ArrayList<All_Request_data_dto> list = new ArrayList<All_Request_data_dto>();
ListView lv;
Button back;
private Spinner spndata;
String[] reqspinner = { "Request Date", "Last Update", "Type", "Owner",
"State" };
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request);
assosiatetoken = MyApplication.getToken();
new doinbackground(this).execute();
back = (Button) findViewById(R.id.button1);
spndata = (Spinner) findViewById(R.id.list_all_quize_req);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, reqspinner);
spndata.setAdapter(adapter);
lv = (ListView) findViewById(R.id.listrequestdata);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Intent edit = new Intent(Request.this, Request_webview.class);
// edit.putExtra("Cat_url", url_link);
startActivity(edit);
}
});
spndata.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch (position) {
case 0:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate1);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).submitDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 1:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).lastModifiedDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 2:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate3);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).state != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 3:
list = DBAdpter.requestUserData(assosiatetoken);
for (int i = 0; i < list.size(); i++) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
break;
default:
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate1 = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.submitDate);
d2 = sdf.parse(ord2.submitDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate3 = new Comparator<All_Request_data_dto>() {
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
String d1 = null;
String d2 = null;
d1 = ord1.state;
d2 = ord2.state;
return d1.compareToIgnoreCase(d2);
}
};
class doinbackground extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
private Context ctx;
public doinbackground(Context c) {
ctx = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ctx);
pd.setMessage("Loading...");
pd.show();
}
#Override
protected Void doInBackground(Void... Params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.cancel();
}
}
public class MyListAdapter extends BaseAdapter {
private ArrayList<All_Request_data_dto> list;
public MyListAdapter(Context mContext,
ArrayList<All_Request_data_dto> list) {
this.list = list;
}
public int getCount() {
return list.size();
}
public All_Request_data_dto getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.custom_request_data, null);
TextView req_id = (TextView) convertView.findViewById(R.id.req_txt);
TextView date = (TextView) convertView.findViewById(R.id.date_txt);
TextView owner = (TextView) convertView
.findViewById(R.id.owner_txt);
TextView state = (TextView) convertView
.findViewById(R.id.state_txt);
req_id.setText(list.get(position).requestId + " - "
+ list.get(position).title);
date.setText(list.get(position).lastModifiedDate + " - "
+ list.get(position).submitDate);
owner.setText(list.get(position).owner);
state.setText(list.get(position).state);
// }
return convertView;
}
}
}
you can make separate list for each category and make a list of these lists and make another list for category names than you can you use ExpandableListView and Adapter for this is like bellow. Here in example, it is used 2d array you can replace this with your list.
public class ExpAdapter extends BaseExpandableListAdapter {
private Context myContext;
String[][] arrChildelements;
String[] arrGroup;
public ExpAdapter(Context context, String[] arrGroup, String[][] arrChild) {
myContext = context;
this.arrGroup = arrGroup;
this.arrChildelements = arrChild;
}
public Object getChild(int groupPosition, int childPosition) {
return null;
}
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
public int getChildrenCount(int groupPosition) {
return arrChildelements[groupPosition].length;
}
public Object getGroup(int groupPosition) {
return null;
}
public int getGroupCount() {
return arrGroup.length;
}
public long getGroupId(int groupPosition) {
return 0;
}
public boolean hasStableIds() {
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_row, null);
}
TextView tvGroupName = (TextView) convertView
.findViewById(R.id.tvGroupName);
tvGroupName.setText(arrGroup[groupPosition]);
return convertView;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_row, null);
}
TextView tvPlayerName = (TextView) convertView
.findViewById(R.id.tvPlayerName);
tvPlayerName.setText(arrChildelements[groupPosition][childPosition]);
return convertView;
}
}
you have to write down your own Adapter. You can extends the BaseAdapter, for instance, and override the following methods:
getCount() it iwill returns the number of items in your dataset
getView() it will inflates your view
getItemViewType() Get the type of View that will be created by getView() (the group element Baroque/Classic in your example) or the "normal" item.
getViewTypeCount () the number of type of Views you have.
I am not sure but if you try to short your list then try this for string
public void sort(List<arraylist> itemLocationList) {
if(itemLocationList!=null)
{
Collections.sort(itemLocationList, new Comparator<arraylist>() {
#Override
public int compare(list o1, list o2) {
return o1.res_name.compareToIgnoreCase(o2.res_name);
}
});
}
}
i got solution on my question .Thanks Jignesh!!!
public class Request extends Activity {
private String assosiatetoken;
private ArrayList<All_Request_data_dto> list = new ArrayList<All_Request_data_dto>();
ListView lv;
ExpandableListView exlistView;
ArrayList<String> catOwner = new ArrayList<String>();
ArrayList<String> uniCatOner = new ArrayList<String>();
ArrayList<ArrayList<All_Request_data_dto>> masterOwner = new ArrayList<ArrayList<All_Request_data_dto>>();
ArrayList<String> catState = new ArrayList<String>();
ArrayList<String> uniCatState = new ArrayList<String>();
ArrayList<ArrayList<All_Request_data_dto>> masterState = new ArrayList<ArrayList<All_Request_data_dto>>();
Button back;
private Spinner spndata;
String[] reqspinner = { "Request Date", "Last Update", "Type", "Owner",
"State" };
ArrayAdapter<String> adapter;
ExpAdapter expAdapter;
private void setOwner() {
for (int i = 0; i < list.size(); i++) {
catOwner.add(list.get(i).owner);
}
HashSet<String> hasSetstate = new HashSet<String>(catOwner);
uniCatOner = new ArrayList<String>(hasSetstate);
for (String str : uniCatOner) {
ArrayList<All_Request_data_dto> cats = new ArrayList<All_Request_data_dto>();
masterOwner.add(cats);
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < uniCatOner.size(); j++) {
if (uniCatOner.get(j).equals(list.get(i).owner)) {
masterOwner.get(j).add(list.get(i));
}
}
}
}
private void setState() {
for (int i = 0; i < list.size(); i++) {
catState.add(list.get(i).state);
}
HashSet<String> hasSetstate = new HashSet<String>(catState);
uniCatState = new ArrayList<String>(hasSetstate);
for (String str1 : uniCatState) {
ArrayList<All_Request_data_dto> cats = new ArrayList<All_Request_data_dto>();
masterState.add(cats);
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < uniCatState.size(); j++) {
if (uniCatState.get(j).equals(list.get(i).state)) {
masterState.get(j).add(list.get(i));
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request);
assosiatetoken = MyApplication.getToken();
list = DBAdpter.requestUserData(assosiatetoken);
exlistView = (ExpandableListView) findViewById(R.id.ExpList);
setOwner();
setState();
new doinbackground(this).execute();
back = (Button) findViewById(R.id.button1);
spndata = (Spinner) findViewById(R.id.list_all_quize_req);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, reqspinner);
spndata.setAdapter(adapter);
lv = (ListView) findViewById(R.id.listrequestdata);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Intent edit = new Intent(Request.this, Request_webview.class);
// edit.putExtra("Cat_url", url_link);
startActivity(edit);
}
});
spndata.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch (position) {
case 0:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate1);
exlistView.setFocusable(false);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).submitDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 1:
list = DBAdpter.requestUserData(assosiatetoken);
exlistView.setVisibility(View.GONE);
Collections.sort(list, byDate);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).lastModifiedDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 2:
list = DBAdpter.requestUserData(assosiatetoken);
exlistView.setVisibility(View.GONE);
Collections.sort(list, byDate3);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).state != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 3:
lv.setVisibility(View.GONE);
expAdapter = new ExpAdapter(Request.this, uniCatOner,
masterOwner);
exlistView.setAdapter(expAdapter);
break;
case 4:
lv.setVisibility(View.GONE);
expAdapter = new ExpAdapter(Request.this, uniCatState,
masterState);
exlistView.setAdapter(expAdapter);
break;
default:
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate1 = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.submitDate);
d2 = sdf.parse(ord2.submitDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate3 = new Comparator<All_Request_data_dto>() {
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
String d1 = null;
String d2 = null;
d1 = ord1.state;
d2 = ord2.state;
return d1.compareToIgnoreCase(d2);
}
};
class doinbackground extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
private Context ctx;
public doinbackground(Context c) {
ctx = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ctx);
pd.setMessage("Loading...");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.cancel();
}
}
public class MyListAdapter extends BaseAdapter {
private ArrayList<All_Request_data_dto> list;
public MyListAdapter(Context mContext,
ArrayList<All_Request_data_dto> list) {
this.list = list;
}
public int getCount() {
return list.size();
}
public All_Request_data_dto getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.custom_request_data, null);
TextView req_id = (TextView) convertView.findViewById(R.id.req_txt);
TextView date = (TextView) convertView.findViewById(R.id.date_txt);
TextView owner = (TextView) convertView
.findViewById(R.id.owner_txt);
TextView state = (TextView) convertView
.findViewById(R.id.state_txt);
req_id.setText(list.get(position).requestId + " - "
+ list.get(position).title);
date.setText(list.get(position).lastModifiedDate + " - "
+ list.get(position).submitDate);
owner.setText(list.get(position).owner);
state.setText(list.get(position).state);
// }
return convertView;
}
}
}
I have a very strange problem while using my ListView.
Only a part of my adapter items are renderd in the listview on screen but when I interact with the listview (ie tries to scroll it) all items are renderd properly.
This fenonemon only occurs if i have less items than the screen can show. Take a look at these screenshots below.
Before interaction:
After interaction:
Source code of activity where adding items:
String[] jRests = getResources().getStringArray(R.array.j_restaurants);
String[] lRests = getResources().getStringArray(R.array.l_restaurants);
items = new ArrayList<Object>();
items.add(getString(R.string.campus_j));
for(String item : jRests){
String[] val = item.split(",,,");
items.add(new FoodSectionListItem(new Restaurant(val[0], val[1], val[2], "")));
}
items.add(getString(R.string.campus_l));
for(String item : lRests){
String[] val = item.split(",,,");
items.add(new FoodSectionListItem(new Restaurant(val[0], val[1], val[2], "")));
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
adapter = new BaseSectionAdapter(this, R.layout.list_item_fragment_header);
if(!isTabletView()){
adapter.setSelectedItem(-1);
}
adapter.setItems(items);
Code of adapter:
public class BaseSectionAdapter extends AmazingAdapter {
private LayoutInflater inflater;
private int selectedItem = 0;
private List<Object> items;
private List<SectionItem> sections = new ArrayList<SectionItem>(10);
private List<Class> itemTypes = new ArrayList<Class>();
private List<Integer> sectionPositions = new ArrayList<Integer>();
private int listHeaderLayoutId;
private View headerView;
public static interface ISectionListItem {
public void setProps(View convertView, int position, int selectedItem);
public View getLayout(LayoutInflater inflater);
}
private class SectionItem implements Serializable {
private static final long serialVersionUID = -8930010937740160935L;
String text;
int position;
public SectionItem(String text, int position) {
this.text = text;
this.position = position;
}
}
public BaseSectionAdapter(Context context, int listHeaderLayoutId) {
this.listHeaderLayoutId = listHeaderLayoutId;
init(context);
}
public BaseSectionAdapter(Context context, int listHeaderLayoutId, List<Object> listItems) {
this.listHeaderLayoutId = listHeaderLayoutId;
init(context);
initListItems(listItems);
}
private void init(Context context) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setSelectedItem(int position) {
selectedItem = position;
}
// public List<ListItem> getItems() {
// return items;
// }
private void initListItems(List<Object> itemList) {
int curSection = -1;
//int curPosition = 0;
//curSection = 0;
this.items = itemList;
itemTypes.clear();
sections.clear();
sectionPositions.clear();
int listSize = itemList.size();
for(int i = 0; i < listSize; i++){
Object currentItem = items.get(i);
if(currentItem instanceof String){
sections.add(new SectionItem((String) currentItem,i));
curSection++;
}
if(!itemTypes.contains(currentItem.getClass())){
itemTypes.add(currentItem.getClass());
}
sectionPositions.add(curSection);
}
Log.d("test", "No of items = "+items.size());
Log.d("test", "No of itemtypes = "+itemTypes.size());
Log.d("test", "View type count = "+getViewTypeCount());
}
public void setItems(List<Object> itemList) {
initListItems(itemList);
}
public int getCount() {
return items==null?0:items.size();
}
#Override
public int getViewTypeCount(){
return (itemTypes.size() == 0)?1:itemTypes.size();
}
#Override
public int getItemViewType(int position){
return itemTypes.indexOf(items.get(position).getClass());
}
#Override
public boolean isEnabled(int position){
return !(items.get(position) instanceof String || items.get(position) instanceof EmptySectionListItem);
}
#Override
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
// TODO Auto-generated method stub
}
#Override
protected void bindSectionHeader(View view, int position,
boolean displaySectionHeader) {
// TextView lSectionTitle = (TextView) view
// .findViewById(R.id.txt_list_header);
// if (displaySectionHeader) {
// lSectionTitle.setVisibility(View.VISIBLE);
// lSectionTitle
// .setText(getSections()[getSectionForPosition(position)]);
// } else {
// lSectionTitle.setVisibility(View.GONE);
// }
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
Object curItemObject = items.get(position);
boolean isHeader = (curItemObject instanceof String);
if(convertView == null){
if(isHeader && headerView != null){
convertView = headerView;
}else if(isHeader){
convertView = inflater.inflate(listHeaderLayoutId, null);
headerView = convertView;
}else{
convertView = ((ISectionListItem) curItemObject).getLayout(inflater);
}
}
if(isHeader){
TextView header = ((TextView)convertView.findViewById(R.id.txt_list_header));
header.setText((String)curItemObject);
}else{
((ISectionListItem)curItemObject).setProps(convertView, position, selectedItem);
}
return convertView;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
TextView textView = ((TextView)header.findViewById(R.id.txt_list_header));
textView.setText(getSections()[getSectionForPosition(position)]);
}
#Override
public int getPositionForSection(int section) {
if(section >= sections.size()){
return 0;
}
return sections.get(section).position;
}
#Override
public int getSectionForPosition(int position) {
return sectionPositions.get(position);
}
#Override
public String[] getSections() {
String[] res = new String[sections.size()];
for (int i = 0; i < res.length; i++) {
res[i] = sections.get(i).text;
}
return res;
}
}
Code of layout:
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
FrameLayout listLayout = new FrameLayout(this);
LinearLayout.LayoutParams listParams = new LinearLayout.LayoutParams(0, FrameLayout.LayoutParams.MATCH_PARENT);
listParams.weight = 1;
listLayout.setId(LIST_FRAGMENT_VIEW_ID);
FrameLayout detailLayout = new FrameLayout(this);
LinearLayout.LayoutParams detailParams = new LinearLayout.LayoutParams(0, FrameLayout.LayoutParams.MATCH_PARENT);
detailParams.weight = 2;
detailLayout.setId(DETAIL_FRAGMENT_VIEW_ID);
layout.addView(listLayout, listParams);
layout.addView(detailLayout, detailParams);
if(savedInstanceState == null){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(listLayout.getId(), (Fragment) listFragment, TWO_PANEL_LIST_FRAGMENT_TAG);
ft.add(detailLayout.getId(), detailFragment);
ft.commit();
}
setContentView(layout);
try calling notifyDataSetChanged() in runOnUIThread() method like I have shown below and it will work like a charm. :)
runOnUiThread(new Runnable() {
#Override
public void run() {
messageAdapter.notifyDataSetChanged();
}
});
i dont know what causes the problem, but if you don't find a logical solution to it you could try something like this:
trigger an onTouchEvent() programmatically whenever you launch the ListView.
scroll down and back up programmatically as soon as the ListView is launched.
etc..
Add ListView widget to layout.xml and add content of list to that. Do not use FrameLayout as it probably is the cause of the problem. It is updating content after touch so the Layout it is on is no implementing the correct onCreate() setup as the ListView widget has.
Are you calling the method notifyDataSetChanged() on your adapter after adding new items? This causes the listview to refresh its view when the underlying dataset is changed.
If it still doesn't work, try notifyDataSetInvalidated() that causes the listview to redraw completely.
Solved it!!!
Problem was with the adapter trying to reuse the same section item. Not good!!!
Changed it to inflate the section item each time we hit a section!