Related
The application which i am creating has an expandable list view in which i have added the option of swipe to edit and delete.I have added those option but when i run the application it doesn't shows the swipe option even i have tried with another list view but there it works fine.
I have used the swipe option inside the base adapter can anyone tell me why the swipe functionality doesn't works in expandable list view.
Expandablelistview:
public class ExpandableHeightListView extends ListView {
private static final int TOUCH_STATE_NONE = 0;
private static final int TOUCH_STATE_X = 1;
private static final int TOUCH_STATE_Y = 2;
public static final int DIRECTION_LEFT = 1;
public static final int DIRECTION_RIGHT = -1;
private int mDirection = 1;//swipe from right to left by default
private int MAX_Y = 5;
private int MAX_X = 3;
private float mDownX;
private float mDownY;
private int mTouchState;
private int mTouchPosition;
private DaybookSwipeMenuLayout mTouchView;
private OnSwipeListener mOnSwipeListener;
private DaybookSwipeMenuCreator mMenuCreator;
private OnMenuItemClickListener mOnMenuItemClickListener;
private OnMenuStateChangeListener mOnMenuStateChangeListener;
private Interpolator mCloseInterpolator;
private Interpolator mOpenInterpolator;
boolean expanded = false;
public ExpandableHeightListView(Context context) {
super(context);
init();
}
public ExpandableHeightListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ExpandableHeightListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
MAX_X = dp2px(MAX_X);
MAX_Y = dp2px(MAX_Y);
mTouchState = TOUCH_STATE_NONE;
}
public boolean isExpanded() {
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isExpanded()) {
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(new DaybookSwipeMenuAdapter(getContext(), adapter) {
#Override
public void createMenu(DaybookSwipeMenu menu) {
if (mMenuCreator != null) {
mMenuCreator.create(menu);
}
}
#Override
public void onItemClick(DaybookSwipeMenuView view, DaybookSwipeMenu menu,
int index) {
boolean flag = false;
if (mOnMenuItemClickListener != null) {
flag = mOnMenuItemClickListener.onMenuItemClick(
view.getPosition(), menu, index);
}
if (mTouchView != null && !flag) {
mTouchView.smoothCloseMenu();
}
}
});
}
public void setCloseInterpolator(Interpolator interpolator) {
mCloseInterpolator = interpolator;
}
public void setOpenInterpolator(Interpolator interpolator) {
mOpenInterpolator = interpolator;
}
public Interpolator getOpenInterpolator() {
return mOpenInterpolator;
}
public Interpolator getCloseInterpolator() {
return mCloseInterpolator;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//在拦截处处理,在滑动设置了点击事件的地方也能swip,点击时又不能影响原来的点击事件
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getX();
mDownY = ev.getY();
boolean handled = super.onInterceptTouchEvent(ev);
mTouchState = TOUCH_STATE_NONE;
mTouchPosition = pointToPosition((int) ev.getX(), (int) ev.getY());
View view = getChildAt(mTouchPosition - getFirstVisiblePosition());
//只在空的时候赋值 以免每次触摸都赋值,会有多个open状态
if (view instanceof DaybookSwipeMenuLayout) {
//如果有打开了 就拦截.
if (mTouchView != null && mTouchView.isOpen() && !inRangeOfView(mTouchView.getMenuView(), ev)) {
return true;
}
mTouchView = (DaybookSwipeMenuLayout) view;
mTouchView.setSwipeDirection(mDirection);
}
//如果摸在另外个view
if (mTouchView != null && mTouchView.isOpen() && view != mTouchView) {
handled = true;
}
if (mTouchView != null) {
mTouchView.onSwipe(ev);
}
return handled;
case MotionEvent.ACTION_MOVE:
float dy = Math.abs((ev.getY() - mDownY));
float dx = Math.abs((ev.getX() - mDownX));
if (Math.abs(dy) > MAX_Y || Math.abs(dx) > MAX_X) {
//每次拦截的down都把触摸状态设置成了TOUCH_STATE_NONE 只有返回true才会走onTouchEvent 所以写在这里就够了
if (mTouchState == TOUCH_STATE_NONE) {
if (Math.abs(dy) > MAX_Y) {
mTouchState = TOUCH_STATE_Y;
} else if (dx > MAX_X) {
mTouchState = TOUCH_STATE_X;
if (mOnSwipeListener != null) {
mOnSwipeListener.onSwipeStart(mTouchPosition);
}
}
}
return true;
}
}
return super.onInterceptTouchEvent(ev);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() != MotionEvent.ACTION_DOWN && mTouchView == null)
return super.onTouchEvent(ev);
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
int oldPos = mTouchPosition;
mDownX = ev.getX();
mDownY = ev.getY();
mTouchState = TOUCH_STATE_NONE;
mTouchPosition = pointToPosition((int) ev.getX(), (int) ev.getY());
if (mTouchPosition == oldPos && mTouchView != null
&& mTouchView.isOpen()) {
mTouchState = TOUCH_STATE_X;
mTouchView.onSwipe(ev);
return true;
}
View view = getChildAt(mTouchPosition - getFirstVisiblePosition());
if (mTouchView != null && mTouchView.isOpen()) {
mTouchView.smoothCloseMenu();
mTouchView = null;
// return super.onTouchEvent(ev);
// try to cancel the touch event
MotionEvent cancelEvent = MotionEvent.obtain(ev);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL);
onTouchEvent(cancelEvent);
if (mOnMenuStateChangeListener != null) {
mOnMenuStateChangeListener.onMenuClose(oldPos);
}
return true;
}
if (view instanceof DaybookSwipeMenuLayout) {
mTouchView = (DaybookSwipeMenuLayout) view;
mTouchView.setSwipeDirection(mDirection);
}
if (mTouchView != null) {
mTouchView.onSwipe(ev);
}
break;
case MotionEvent.ACTION_MOVE:
//有些可能有header,要减去header再判断
mTouchPosition = pointToPosition((int) ev.getX(), (int) ev.getY()) - getHeaderViewsCount();
//如果滑动了一下没完全展现,就收回去,这时候mTouchView已经赋值,再滑动另外一个不可以swip的view
//会导致mTouchView swip 。 所以要用位置判断是否滑动的是一个view
if (!mTouchView.getSwipEnable() || mTouchPosition != mTouchView.getPosition()) {
break;
}
float dy = Math.abs((ev.getY() - mDownY));
float dx = Math.abs((ev.getX() - mDownX));
if (mTouchState == TOUCH_STATE_X) {
if (mTouchView != null) {
mTouchView.onSwipe(ev);
}
getSelector().setState(new int[]{0});
ev.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(ev);
return true;
} else if (mTouchState == TOUCH_STATE_NONE) {
if (Math.abs(dy) > MAX_Y) {
mTouchState = TOUCH_STATE_Y;
} else if (dx > MAX_X) {
mTouchState = TOUCH_STATE_X;
if (mOnSwipeListener != null) {
mOnSwipeListener.onSwipeStart(mTouchPosition);
}
}
}
break;
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_STATE_X) {
if (mTouchView != null) {
boolean isBeforeOpen = mTouchView.isOpen();
mTouchView.onSwipe(ev);
boolean isAfterOpen = mTouchView.isOpen();
if (isBeforeOpen != isAfterOpen && mOnMenuStateChangeListener != null) {
if (isAfterOpen) {
mOnMenuStateChangeListener.onMenuOpen(mTouchPosition);
} else {
mOnMenuStateChangeListener.onMenuClose(mTouchPosition);
}
}
if (!isAfterOpen) {
mTouchPosition = -1;
mTouchView = null;
}
}
if (mOnSwipeListener != null) {
mOnSwipeListener.onSwipeEnd(mTouchPosition);
}
ev.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(ev);
return true;
}
break;
}
return super.onTouchEvent(ev);
}
public void smoothOpenMenu(int position) {
if (position >= getFirstVisiblePosition()
&& position <= getLastVisiblePosition()) {
View view = getChildAt(position - getFirstVisiblePosition());
if (view instanceof DaybookSwipeMenuLayout) {
mTouchPosition = position;
if (mTouchView != null && mTouchView.isOpen()) {
mTouchView.smoothCloseMenu();
}
mTouchView = (DaybookSwipeMenuLayout) view;
mTouchView.setSwipeDirection(mDirection);
mTouchView.smoothOpenMenu();
}
}
}
public void smoothCloseMenu(){
if (mTouchView != null && mTouchView.isOpen()) {
mTouchView.smoothCloseMenu();
}
}
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getContext().getResources().getDisplayMetrics());
}
public void setMenuCreator(DaybookSwipeMenuCreator menuCreator) {
this.mMenuCreator = menuCreator;
}
public void setOnMenuItemClickListener(
OnMenuItemClickListener onMenuItemClickListener) {
this.mOnMenuItemClickListener = onMenuItemClickListener;
}
public void setOnSwipeListener(OnSwipeListener onSwipeListener) {
this.mOnSwipeListener = onSwipeListener;
}
public void setOnMenuStateChangeListener(OnMenuStateChangeListener onMenuStateChangeListener) {
mOnMenuStateChangeListener = onMenuStateChangeListener;
}
public static interface OnMenuItemClickListener {
boolean onMenuItemClick(int position, DaybookSwipeMenu menu, int index);
}
public static interface OnSwipeListener {
void onSwipeStart(int position);
void onSwipeEnd(int position);
}
public static interface OnMenuStateChangeListener {
void onMenuOpen(int position);
void onMenuClose(int position);
}
public void setSwipeDirection(int direction) {
mDirection = direction;
}
/**
* 判断点击事件是否在某个view内
*
* #param view
* #param ev
* #return
*/
public static boolean inRangeOfView(View view, MotionEvent ev) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
if (ev.getRawX() < x || ev.getRawX() > (x + view.getWidth()) || ev.getRawY() < y || ev.getRawY() > (y + view.getHeight())) {
return false;
}
return true;
}
BaseAdapter class having the swipe list option:
public class Daybook_adapter extends BaseAdapter {
Context context;
ArrayList<Daybook> entriesdaybook;
ArrayList<Daybooklist> daybooklists;
Daybooklist_adapter adapter;
DatabaseHandler databaseHandler;
LinearLayout emptyy;
double totalamountin=0.0;
ExpandableHeightListView daybookdetailviewlist;
public Daybook_adapter(Context context, ArrayList<Daybook> list) {
this.context = context;
entriesdaybook = list;
}
#Override
public int getCount() {
return entriesdaybook.size();
}
#Override
public Object getItem(int position) {
return entriesdaybook.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.model_daybook, null);
}
Daybook m = entriesdaybook.get(position);
final TextView tv_date = (TextView) convertView.findViewById(R.id.tv_daybook_date);
final TextView tv_cashin = (TextView) convertView.findViewById(R.id.tv_daybook_cashin);
final TextView tv_cashout = (TextView) convertView.findViewById(R.id.tv_daybook_cashout);
final TextView tv_totalamt = (TextView)convertView.findViewById(R.id.daybook_total_amt);
//final String s = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String s = m.getDate();
emptyy = (LinearLayout) convertView.findViewById(R.id.empty);
daybookdetailviewlist = (ExpandableHeightListView) convertView.findViewById(R.id.detaillist_daybook);
String[] spiliter = s.split("-");
String year = spiliter[0];
String month = spiliter[1];
String date = spiliter[2];
if (month.startsWith("01")) {
tv_date.setText(date + "Jan" + year);
} else if (month.startsWith("02")) {
tv_date.setText(date + "Feb" + year);
} else if (month.startsWith("03")) {
tv_date.setText(date + "Mar" + year);
} else if (month.startsWith("04")) {
tv_date.setText(date + "Apr" + year);
} else if (month.startsWith("05")) {
tv_date.setText(date + "May" + year);
} else if (month.startsWith("06")) {
tv_date.setText(date + "Jun" + year);
} else if (month.startsWith("07")) {
tv_date.setText(date + "Jul" + year);
} else if (month.startsWith("08")) {
tv_date.setText(date + "Aug" + year);
} else if (month.startsWith("09")) {
tv_date.setText(date + "Sep" + year);
} else if (month.startsWith("10")) {
tv_date.setText(date + "Oct" + year);
} else if (month.startsWith("11")) {
tv_date.setText(date + "Nov" + year);
} else if (month.startsWith("12")) {
tv_date.setText(date + "Dec" + year);
}
/* if (m.getUsertype().startsWith("singleworker")) {
tv_cashin.setText("\u20B9" + "0");
} else if (m.getUsertype().startsWith("groupworker")) {
tv_cashin.setText("\u20B9" + "0");
}*/
tv_cashin.setText("\u20B9" + m.getCashin());
tv_cashout.setText("\u20B9" + m.getCashout());
double one = Double.parseDouble(m.getCashin());
double two = Double.parseDouble(m.getCashout());
double three = one+two;
tv_totalamt.setText("\u20B9" +String.valueOf(three) );
databaseHandler = new DatabaseHandler(context);
daybooklists = databaseHandler.getAllDaywisedaybookdetails(s);
adapter = new Daybooklist_adapter((Activity) context, daybooklists);
if (adapter != null) {
if (adapter.getCount() > 0) {
emptyy.setVisibility(View.GONE);
daybookdetailviewlist.setAdapter(adapter);
DaybookSwipeMenuCreator creator = new DaybookSwipeMenuCreator() {
#Override
public void create(DaybookSwipeMenu menu) {
// create "open" item
DaybookSwipeMenuItem openItem = new DaybookSwipeMenuItem(
(Activity) context);
// set item background
openItem.setBackground(R.color.colorPrimary);
// set item width
openItem.setWidth(dp2px(90));
// set item title
openItem.setIcon(context.getResources().getDrawable(R.drawable.pencil));
openItem.setTitle("Edit");
// set item title fontsize
openItem.setTitleSize(15);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
// create "delete" item
DaybookSwipeMenuItem deleteItem = new DaybookSwipeMenuItem(
(Activity) context);
// set item background
deleteItem.setBackground(R.color.colorPrimaryDark);
// set item width
deleteItem.setWidth(dp2px(90));
// set a icon
deleteItem.setIcon(context.getResources().getDrawable(R.drawable.delete));
deleteItem.setTitle("Delete");
deleteItem.setTitleSize(15);
deleteItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(deleteItem);
}
};
daybookdetailviewlist.setMenuCreator(creator);
final ArrayList<Daybooklist> finalListet = daybooklists;
daybookdetailviewlist.setOnMenuItemClickListener(new ExpandableHeightListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(final int position, DaybookSwipeMenu menu, int index) {
// Coconuttype item = finalListet.get(position);
// final String farmername = finalListet.get(position).getFarmername();
// final String farmermobno = finalListet.get(position).getFarmermobno();
// final String farmerlocation = finalListet.get(position).getFarmerlocation();
switch (index) {
case 0:
// open
// open(item);
// String farmername = finalListet.get(position).getFarmername();
// String farmermobno = finalListet.get(position).getFarmermobno();
// String farmerlocation =finalListet.get(position).getFarmerlocation();
Log.e("Editclicked", "edt");
// Log.e("farmername", farmername);
// Log.e("farmermobno", farmermobno);
// Log.e("farmerlocation", farmerlocation);
/* Intent k = new Intent(context, FarmerEdit_Activity.class);
k.putExtra("farmername", farmername);
k.putExtra("farmermobno", farmermobno);
k.putExtra("farmerlocation", farmerlocation);
context.startActivity(k);*/
break;
case 1:
// delete
//delete(item);
Log.e("Deleteclicked", "del");
AlertDialog.Builder alert = new AlertDialog.Builder(
context);
alert.setTitle("Delete");
alert.setMessage("Are you sure to delete ");
alert.setPositiveButton(context.getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do your work here
finalListet.remove(position);
//databaseHandlerOtherChgs.deleteCoconut(item.getCoconuttype());
// Log.e("farmername", farmername);
// Log.e("farmermobno", farmermobno);
// Log.e("farmerlocation", farmerlocation);
/* databasehandler.deletefarmercontacts(farmername, farmermobno);
databasehandler.deletedaybookdetails(farmername, farmermobno);
databasehandler.deletefarmeradvance(farmername, farmermobno);
databasehandler.deletefarmerbillbookdetails(farmername, farmermobno);
databasehandler.deletefarmertradedetails(farmername, farmermobno);
fadapter.notifyDataSetChanged();
Intent k = getIntent();
finish();
startActivity(k);*/
}
});
alert.setNegativeButton(context.getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
/* finalListet.remove(position);
databaseHandlerOtherChgs.deleteCoconut(item.getCoconuttype());
adapter.notifyDataSetChanged();
Intent k = getIntent();
finish();
startActivity(k);*/
break;
}
return false;
}
});
// set SwipeListener
daybookdetailviewlist.setOnSwipeListener(new ExpandableHeightListView.OnSwipeListener() {
#Override
public void onSwipeStart(int position) {
// swipe start
}
#Override
public void onSwipeEnd(int position) {
// swipe end
}
});
// set MenuStateChangeListener
daybookdetailviewlist.setOnMenuStateChangeListener(new ExpandableHeightListView.OnMenuStateChangeListener() {
#Override
public void onMenuOpen(int position) {
}
#Override
public void onMenuClose(int position) {
}
});
}
}else {
daybookdetailviewlist.setEmptyView(emptyy);
}
daybookdetailviewlist.setExpanded(true);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//todo disable the comments for farmer individual transaction
}
});
return convertView;
}
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
context.getResources().getDisplayMetrics());
}
public void setTransactionList(ArrayList<Daybook> newList) {
entriesdaybook = newList;
notifyDataSetChanged();
}
}
I m posting code here , i hope it helps u
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">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:focusable="false"
android:text="Click this:notify data set changed and re-open the opened menu" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/btn">
<com.allen.expandablelistview.SwipeMenuExpandableListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_below="#id/btn"
android:groupIndicator="#null" />
</FrameLayout>
</RelativeLayout>
MainActivity.java :
public class MainActivity extends AppCompatActivity {
private List<ApplicationInfo> mAppList;
private AppAdapter mAdapter;
private SwipeMenuExpandableListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppList = getPackageManager().getInstalledApplications(0);
findViewById(R.id.btn).setOnClickListener(l);
// 1. Create View
listView = (SwipeMenuExpandableListView) findViewById(R.id.listView);
if (getIntent().getBooleanExtra("stick_mode", false)) {
// 2. Set where does the menu item stick with
/**
* STICK_TO_ITEM_RIGHT_SIDE: Stick with item right side, when swipe,
* it moves from outside of screen .
**/
/**
* STICK_TO_SCREEN: stick with the screen, it was covered and don't
* move ,item moves then menu show.
**/
listView.setmMenuStickTo(SwipeMenuListView.STICK_TO_SCREEN);
}
// 3. Create Adapter and set. It controls data,
// item view,clickable ,swipable ...
mAdapter = new AppAdapter();
listView.setAdapter(mAdapter);
// 4. Set OnItemLongClickListener
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int itemType = ExpandableListView.getPackedPositionType(id);
int childPosition, groupPosition;
if (itemType == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
childPosition = ExpandableListView.getPackedPositionChild(id);
groupPosition = ExpandableListView.getPackedPositionGroup(id);
// do your per-item callback here
Toast.makeText(MainActivity.this,
"long click on group " + groupPosition + " child " + childPosition, Toast.LENGTH_SHORT)
.show();
return true; // true if we consumed the click, false if not
} else if (itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
groupPosition = ExpandableListView.getPackedPositionGroup(id);
// do your per-group callback here
Toast.makeText(MainActivity.this, "long click on group " + groupPosition,
Toast.LENGTH_SHORT).show();
return true; // true if we consumed the click, false if not
} else {
// null item; we don't consume the click
return false;
}
}
});
// 5.Set OnGroupClickListener
listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
Toast.makeText(MainActivity.this, "group " + groupPosition + " clicked", Toast.LENGTH_SHORT)
.show();
return false;
}
});
// 6.Set OnChildClickListener
listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Toast.makeText(MainActivity.this,
"group " + groupPosition + " child " + childPosition + " clicked", Toast.LENGTH_SHORT).show();
return false;
}
});
// 7. Create and set a SwipeMenuExpandableCreator
// define the group and child creator function
SwipeMenuExpandableCreator creator = new SwipeMenuExpandableCreator() {
#Override
public void createGroup(SwipeMenu menu) {
// Create different menus depending on the view type
switch (menu.getViewType()) {
case 0:
createMenu1(menu);
break;
case 1:
createMenu2(menu);
break;
case 2:
createMenu3(menu);
break;
}
}
#Override
public void createChild(SwipeMenu menu) {
// Create different menus depending on the view type
switch (menu.getViewType()) {
case 0:
createMenu1(menu);
break;
case 1:
createMenu2(menu);
break;
case 2:
createMenu3(menu);
break;
}
}
private void createMenu1(SwipeMenu menu) {
SwipeMenuItem item1 = new SwipeMenuItem(getApplicationContext());
item1.setBackground(new ColorDrawable(Color.rgb(0xE5, 0x18, 0x5E)));
item1.setWidth(dp2px(90));
item1.setIcon(R.drawable.ic_action_favorite);
menu.addMenuItem(item1);
SwipeMenuItem item2 = new SwipeMenuItem(getApplicationContext());
item2.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
item2.setWidth(dp2px(90));
item2.setIcon(R.drawable.ic_action_good);
menu.addMenuItem(item2);
}
private void createMenu2(SwipeMenu menu) {
SwipeMenuItem item1 = new SwipeMenuItem(getApplicationContext());
item1.setBackground(new ColorDrawable(Color.rgb(0xE5, 0xE0, 0x3F)));
item1.setWidth(dp2px(90));
item1.setIcon(R.drawable.ic_action_important);
menu.addMenuItem(item1);
SwipeMenuItem item2 = new SwipeMenuItem(getApplicationContext());
item2.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
item2.setWidth(dp2px(90));
item2.setIcon(R.drawable.ic_action_discard);
menu.addMenuItem(item2);
}
private void createMenu3(SwipeMenu menu) {
SwipeMenuItem item1 = new SwipeMenuItem(getApplicationContext());
item1.setBackground(new ColorDrawable(Color.rgb(0x30, 0xB1, 0xF5)));
item1.setWidth(dp2px(90));
item1.setIcon(R.drawable.ic_action_about);
menu.addMenuItem(item1);
SwipeMenuItem item2 = new SwipeMenuItem(getApplicationContext());
item2.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
item2.setWidth(dp2px(90));
item2.setIcon(R.drawable.ic_action_share);
menu.addMenuItem(item2);
}
};
listView.setMenuCreator(creator);
// 8. Set OnMenuItemClickListener
listView.setOnMenuItemClickListener(new SwipeMenuExpandableListView.OnMenuItemClickListenerForExpandable() {
#Override
public boolean onMenuItemClick(int groupPostion, int childPostion, SwipeMenu menu, int index) {
ApplicationInfo item = mAppList.get(groupPostion);
// childPostion == -1991 means it was the group's swipe menu was
// clicked
String s = "Group " + groupPostion;
if (childPostion != SwipeMenuExpandableListAdapter.GROUP_INDEX) {
s += " , child " + childPostion;
}
s += " , menu index:" + index + " was clicked";
switch (index) {
case 0:
// open
break;
case 1:
// delete
// delete(item);
mAppList.remove(groupPostion);
mAdapter.notifyDataSetChanged();
break;
}
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
return false;
}
});
}
public void btnClick(View view) {
}
/**
* Basically, it's the same as BaseExpandableListAdapter. But added controls
* to every item's swipability
*
* #author yuchentang
* #see android.widget.BaseExpandableListAdapter
*/
class AppAdapter extends BaseSwipeMenuExpandableListAdapter {
/**
* Whether this group item swipable
*
* #param groupPosition
* #return
* #see com.allen.expandablelistview.BaseSwipeMenuExpandableListAdapter#isGroupSwipable(int)
*/
#Override
public boolean isGroupSwipable(int groupPosition) {
return true;
}
/**
* Whether this child item swipable
*
* #param groupPosition
* #param childPosition
* #return
* #see com.allen.expandablelistview.BaseSwipeMenuExpandableListAdapter#isChildSwipable(int,
* int)
*/
#Override
public boolean isChildSwipable(int groupPosition, int childPosition) {
if (childPosition == 0)
return false;
return true;
}
#Override
public int getChildType(int groupPosition, int childPosition) {
return childPosition % 3;
}
#Override
public int getChildTypeCount() {
return 3;
}
#Override
public int getGroupType(int groupPosition) {
return groupPosition % 3;
}
#Override
public int getGroupTypeCount() {
return 3;
}
class ViewHolder {
ImageView iv_icon;
TextView tv_name;
public ViewHolder(View view) {
iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
tv_name = (TextView) view.findViewById(R.id.tv_name);
view.setTag(this);
}
}
#Override
public int getGroupCount() {
return mAppList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return 3;
}
#Override
public Object getGroup(int groupPosition) {
return mAppList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return "The " + childPosition + "'th child in " + groupPosition + "'th group.";
}
#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 ContentViewWrapper getGroupViewAndReUsable(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
boolean reUseable = true;
if (convertView == null) {
convertView = View.inflate(getApplicationContext(), R.layout.item_list_app, null);
convertView.setTag(new ViewHolder(convertView));
reUseable = false;
}
ViewHolder holder = (ViewHolder) convertView.getTag();
ApplicationInfo item = (ApplicationInfo) getGroup(groupPosition);
holder.iv_icon.setImageDrawable(item.loadIcon(getPackageManager()));
holder.tv_name.setText(item.loadLabel(getPackageManager()));
return new ContentViewWrapper(convertView, reUseable);
}
#Override
public ContentViewWrapper getChildViewAndReUsable(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
boolean reUseable = true;
if (convertView == null) {
convertView = View.inflate(getApplicationContext(), R.layout.item_list_app, null);
convertView.setTag(new ViewHolder(convertView));
reUseable = false;
}
ViewHolder holder = (ViewHolder) convertView.getTag();
if (null == holder) {
holder = new ViewHolder(convertView);
}
ApplicationInfo item = (ApplicationInfo) getGroup(groupPosition);
convertView.setBackgroundColor(Color.GRAY);
holder.iv_icon.setImageDrawable(item.loadIcon(getPackageManager()));
holder.tv_name.setText("this is child");
return new ContentViewWrapper(convertView, reUseable);
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
View.OnClickListener l = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mAdapter.notifyDataSetChanged(true);
}
};
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
}
Hereby, i am attaching screenshot
Try this Code,
https://github.com/tycallen/SwipeMenu-Expandable-ListView.
Download and Import to Android studio.
I have a RelativeLayout which has a ViewDragHelper which I use to move the view around. I have to use layout(boolean changed, int left, int top, int right, int bottom) to update view size on drag because the views inside need to resize. This all works fine. Now the child views inside have their touch positions all wrong. Buttons work as if they were on top of the screen as opposed to where they are.
private void changeDragViewPosition(int top, float verticalMovementFactor) {
int right = calculateViewRightPosition(verticalMovementFactor);
int left = right - mainViewLayoutParams.width;
int bottom = top + mainViewLayoutParams.height;
mainView.layout(left, top, right, bottom);
}
This is the code I use for moving the view. The mainView itself has correct touch positions, the child views inside this view are the problem. Is there anything I'm missing?
EDIT
Here is the view i'm using.
public class MinimizableView extends RelativeLayout {
private static final int DEFAULT_MINIMIZED_MARGIN = 2;
private static final int DEFAULT_SCALE_FACTOR = 2;
private static final int MIN_SLIDING_DISTANCE_ON_CLICK = 10;
private View mainView;
private View unmovableView;
private ArrayList<View> otherViews;
private ArrayList<Integer> initialPositions;
private LayoutParams mainViewLayoutParams;
private int verticalDragRange;
private int mainViewOriginalWidth;
private int mainViewOriginalHeight;
private float scaleFactor = DEFAULT_SCALE_FACTOR;
private float minimizedMargin;
private boolean firstLayoutPass = true;
private int mainViewInitialPosition;
private float lastTouchActionDownXPosition;
private ViewDragHelper viewDragHelper;
private MinimizableViewListener listener;
public interface MinimizableViewListener {
void onMinimized();
void onMaximized();
void onClosed();
}
public MinimizableView(Context context) {
super(context);
init(context);
}
public MinimizableView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MinimizableView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
minimizedMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_MINIMIZED_MARGIN, getResources().getDisplayMetrics());
ViewCompat.requestApplyInsets(this);
}
private ViewDragHelper.Callback viewDragHelperCallback = new ViewDragHelper.Callback() {
private static final int MINIMUM_DX_FOR_HORIZONTAL_DRAG = 5;
private static final int MINIMUM_DY_FOR_VERTICAL_DRAG = 15;
private static final float X_MIN_VELOCITY = 1500;
private static final float Y_MIN_VELOCITY = 1000;
#Override
public boolean tryCaptureView(View child, int pointerId) {
return child.equals(mainView);
}
#Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
if (!isMainViewAtBottom()) {
float verticalMovementFactor = (top - mainViewInitialPosition) / (float) verticalDragRange;
changeDragViewScale(verticalMovementFactor);
changeDragViewPosition(top, verticalMovementFactor);
changeSecondViewAlpha(verticalMovementFactor);
changeSecondViewPosition(verticalMovementFactor);
changeUnmovableViewAlpha(verticalMovementFactor);
}
}
#Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
super.onViewReleased(releasedChild, xvel, yvel);
if (isMainViewAtBottom() && !isViewAtRight(releasedChild)) {
triggerOnReleaseActionsWhileHorizontalDrag(xvel);
} else {
triggerOnReleaseActionsWhileVerticalDrag(yvel);
}
}
#Override
public int clampViewPositionVertical(View child, int top, int dy) {
int newTop = verticalDragRange + mainViewInitialPosition;
if (isMinimized() && Math.abs(dy) >= MINIMUM_DY_FOR_VERTICAL_DRAG || (!isMinimized() && !isMainViewAtBottom())) {
final int topBound = getPaddingTop() + mainViewInitialPosition;
final int bottomBound = verticalDragRange + mainViewInitialPosition;
newTop = Math.min(Math.max(top, topBound), bottomBound);
}
return newTop;
}
#Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
int newLeft = mainView.getLeft();
if ((isMinimized() && Math.abs(dx) > MINIMUM_DX_FOR_HORIZONTAL_DRAG) || (isMainViewAtBottom() && !isViewAtRight(mainView))) {
newLeft = left;
}
return newLeft;
}
private void triggerOnReleaseActionsWhileHorizontalDrag(float xvel) {
if (xvel < 0 && xvel <= -X_MIN_VELOCITY) {
closeToLeft();
} else if (xvel > 0 && xvel >= X_MIN_VELOCITY) {
closeToRight();
} else {
if (isNextToLeftBound(mainView)) {
closeToLeft();
} else if (isNextToRightBound(mainView)) {
closeToRight();
} else {
minimize();
}
}
}
private void triggerOnReleaseActionsWhileVerticalDrag(float xvel) {
if (xvel < 0 && xvel <= -Y_MIN_VELOCITY) {
maximize();
} else if (xvel > 0 && xvel >= Y_MIN_VELOCITY) {
minimize();
} else {
if (isDragViewAboveTheMiddle(mainView)) {
maximize();
} else {
minimize();
}
}
}
};
private void changeDragViewScale(float verticalMovementFactor) {
mainViewLayoutParams.width = (int) (mainViewOriginalWidth * (1 - (verticalMovementFactor / scaleFactor)));
mainViewLayoutParams.height = (int) (mainViewOriginalHeight * (1 - (verticalMovementFactor / scaleFactor)));
mainView.setLayoutParams(mainViewLayoutParams);
}
private void changeDragViewPosition(int top, float verticalMovementFactor) {
int right = calculateViewRightPosition(verticalMovementFactor);
int left = right - mainViewLayoutParams.width;
int bottom = top + mainViewLayoutParams.height;
mainView.layout(left, top, right, bottom);
}
private void changeSecondViewAlpha(float verticalMovementFactor) {
for (int i = 0; i < otherViews.size(); i++) {
otherViews.get(i).setAlpha(1 - verticalMovementFactor);
}
}
private void changeSecondViewPosition(float verticalMovementFactor) {
int newTop;
int initialTop;
for (int i = 0; i < otherViews.size(); i++) {
initialTop = initialPositions.get(i);
newTop = (int) (initialTop + ((getBottom() - initialTop) * verticalMovementFactor));
otherViews.get(i).setY(newTop);
}
}
private void changeUnmovableViewAlpha(float verticalMovementFactor) {
unmovableView.setAlpha(1 - verticalMovementFactor);
}
private int calculateViewRightPosition(float verticalMoveFactor) {
return (int) (mainViewOriginalWidth - minimizedMargin * verticalMoveFactor);
}
private boolean isDragViewAboveTheMiddle(View view) {
int parentHeight = getHeight();
float viewYPosition = view.getY() + (view.getHeight() * 0.5f);
return viewYPosition < (parentHeight * 0.5);
}
private boolean isMainViewAtTop() {
return mainView.getTop() == mainViewInitialPosition;
}
private boolean isMainViewAtBottom() {
return mainView.getBottom() >= getBottom() - getPaddingBottom() - minimizedMargin - 1;
}
private boolean isViewAtRight(View view) {
return view.getRight() + minimizedMargin + 10 >= getWidth() - 10;
}
private void closeToLeft() {
if (viewDragHelper.smoothSlideViewTo(mainView, -mainViewOriginalWidth, getHeight() - getMinHeightPlusMargin())) {
ViewCompat.postInvalidateOnAnimation(this);
}
if (listener != null) {
listener.onClosed();
}
}
private int getMinHeightPlusMargin() {
return (int) (mainViewOriginalHeight * (1 - 1 / scaleFactor) + minimizedMargin);
}
private int getMinWidthPlusMargin() {
return (int) (mainViewOriginalWidth * (1 - 1 / scaleFactor) + minimizedMargin);
}
private void closeToRight() {
if (viewDragHelper.smoothSlideViewTo(mainView, mainViewOriginalWidth, getHeight() - getMinHeightPlusMargin())) {
ViewCompat.postInvalidateOnAnimation(this);
}
if (listener != null) {
listener.onClosed();
}
}
private boolean isNextToLeftBound(View view) {
return (view.getLeft() - minimizedMargin) < getWidth() * 0.05;
}
private boolean isNextToRightBound(View view) {
return (view.getLeft() - minimizedMargin) > getWidth() * 0.75;
}
private boolean isViewHit(View view, int x, int y) {
int[] viewLocation = new int[2];
view.getLocationOnScreen(viewLocation);
int[] parentLocation = new int[2];
this.getLocationOnScreen(parentLocation);
int screenX = parentLocation[0] + x;
int screenY = parentLocation[1] + y;
return screenX >= viewLocation[0]
&& screenX < viewLocation[0] + view.getWidth()
&& screenY >= viewLocation[1]
&& screenY < viewLocation[1] + view.getHeight();
}
private static final int INVALID_POINTER = -1;
private int activePointerId;
#Override
public boolean onTouchEvent(MotionEvent event) {
int actionMasked = MotionEventCompat.getActionMasked(event);
if ((actionMasked & MotionEventCompat.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
activePointerId = MotionEventCompat.getPointerId(event, actionMasked);
}
if (activePointerId == INVALID_POINTER) {
return false;
}
viewDragHelper.processTouchEvent(event);
if (isClosed()) {
return false;
}
boolean isDragViewHit = isViewHit(mainView, (int) event.getX(), (int) event.getY());
boolean isSecondViewHit = false;
for (int i = 0; i < otherViews.size(); i++) {
if (isViewHit(otherViews.get(i), (int) event.getX(), (int) event.getY())) {
isSecondViewHit = true;
break;
}
}
analyzeTouchToMaximizeIfNeeded(event, isDragViewHit);
if (isMaximized()) {
mainView.dispatchTouchEvent(event);
} else {
mainView.dispatchTouchEvent(cloneMotionEventWithAction(event, MotionEvent.ACTION_CANCEL));
}
return isDragViewHit || isSecondViewHit;
}
private void analyzeTouchToMaximizeIfNeeded(MotionEvent ev, boolean isDragViewHit) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lastTouchActionDownXPosition = ev.getX();
break;
case MotionEvent.ACTION_UP:
float clickOffset = ev.getX() - lastTouchActionDownXPosition;
if (shouldMaximizeOnClick(ev, clickOffset, isDragViewHit)) {
if (isMinimized()) {
maximize();
}
}
break;
default:
break;
}
}
public boolean shouldMaximizeOnClick(MotionEvent ev, float deltaX, boolean isDragViewHit) {
return (Math.abs(deltaX) < MIN_SLIDING_DISTANCE_ON_CLICK) && ev.getAction() != MotionEvent.ACTION_MOVE && isDragViewHit;
}
private MotionEvent cloneMotionEventWithAction(MotionEvent event, int action) {
return MotionEvent.obtain(event.getDownTime(), event.getEventTime(), action, event.getX(), event.getY(), event.getMetaState());
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!isEnabled()) {
return false;
}
switch (MotionEventCompat.getActionMasked(ev) & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
viewDragHelper.cancel();
return false;
case MotionEvent.ACTION_DOWN:
int index = MotionEventCompat.getActionIndex(ev);
activePointerId = MotionEventCompat.getPointerId(ev, index);
if (activePointerId == INVALID_POINTER) {
return false;
}
break;
default:
break;
}
boolean interceptTap = viewDragHelper.isViewUnder(mainView, (int) ev.getX(), (int) ev.getY());
return viewDragHelper.shouldInterceptTouchEvent(ev) || interceptTap;
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
otherViews = new ArrayList<>();
initialPositions = new ArrayList<>();
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child instanceof DragView) {
mainView = child;
} else if (child instanceof UnmovableView) {
unmovableView = child;
} else {
otherViews.add(child);
}
}
viewDragHelper = ViewDragHelper.create(this, 1, viewDragHelperCallback);
mainViewLayoutParams = (LayoutParams) mainView.getLayoutParams();
}
#Override
public void computeScroll() {
if (!isInEditMode() && viewDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (isInEditMode() || firstLayoutPass) {
super.onLayout(changed, left, top, right, bottom);
mainViewInitialPosition = mainView.getTop();
verticalDragRange = getMeasuredHeight() - mainViewInitialPosition - getMinHeightPlusMargin() - getPaddingTop() - getPaddingBottom();
for (int i = 0; i < otherViews.size(); i++) {
initialPositions.add(otherViews.get(i).getTop());
}
firstLayoutPass = false;
} else if (isMainViewAtTop()) {
mainView.layout(left, mainViewInitialPosition, right, mainViewInitialPosition + mainViewOriginalHeight);
changeUnmovableViewAlpha(0);
setLayoutPositions(0, left, right, bottom, true);
} else {
setLayoutPositions(mainView.getTop() / (float) verticalDragRange, left, right, bottom, false);
}
}
private void setLayoutPositions(float offsetFactor, int left, int right, int bottom, boolean setY) {
int newTop;
int initialTop;
for (int i = 0; i < otherViews.size(); i++) {
View view = otherViews.get(i);
initialTop = initialPositions.get(i);
newTop = (int) (initialTop + ((bottom - initialTop) * offsetFactor));
view.layout(left, newTop, right, newTop + view.getHeight());
if (setY) {
view.setY(newTop);
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mainViewOriginalWidth == 0) {
mainViewOriginalWidth = mainView.getMeasuredWidth();
mainViewOriginalHeight = mainView.getMeasuredHeight();
}
}
private boolean smoothSlideTo(float slideOffset) {
final int topBound = mainViewInitialPosition + getPaddingTop();
int x = (int) (slideOffset * (getWidth() - getMinWidthPlusMargin()));
int y = (int) ((slideOffset * verticalDragRange) + topBound);
if (viewDragHelper.smoothSlideViewTo(mainView, x, y)) {
ViewCompat.postInvalidateOnAnimation(this);
return true;
}
return false;
}
#Override
public void setPadding(int left, int top, int right, int bottom) {
super.setPadding(left, top, right, bottom);
mainViewInitialPosition = mainView.getTop();
verticalDragRange = getMeasuredHeight() - mainViewInitialPosition - getMinHeightPlusMargin() - getPaddingTop() - getPaddingBottom();
for (int i = 0; i < otherViews.size(); i++) {
initialPositions.add(otherViews.get(i).getTop());
}
}
// --------- PUBLIC METHODS ---------- //
public void maximize() {
smoothSlideTo(0);
if (listener != null) {
listener.onMaximized();
}
}
public void minimize() {
smoothSlideTo(1);
if (listener != null) {
listener.onMinimized();
}
}
public boolean isMinimized() {
return isMainViewAtBottom() && isViewAtRight(mainView);
}
public boolean isMaximized() {
return mainView.getTop() == mainViewInitialPosition;
}
public boolean isClosed() {
return mainView.getRight() <= 0 && mainView.getLeft() >= getWidth();
}
public void setMinimizableViewListener(MinimizableViewListener listener) {
this.listener = listener;
}
public void hide() {
changeDragViewScale(1);
changeDragViewPosition(verticalDragRange + mainViewInitialPosition - getMinHeightPlusMargin(), 1);
minimize();
setVisibility(GONE);
}
public void show() {
setVisibility(VISIBLE);
post(new Runnable() {
#Override
public void run() {
maximize();
}
});
}
}
As you can see the I have overridden the onTouch method and it works fine. I also have a button inside the mainView which is also a RelativeLayout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lycatv.dragviewtest.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/actionBar1"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/actionBar1"
android:fitsSystemWindows="true"
android:text="Hello World!" />
<com.lycatv.dragviewtest.MinimizableView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="56dp">
<com.lycatv.dragviewtest.UnmovableView
android:id="#+id/actionBar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark" />
</com.lycatv.dragviewtest.UnmovableView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/actionBar"
android:background="#1a1e39" />
<FrameLayout
android:id="#+id/frameLayout1"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_below="#+id/actionBar" />
<com.lycatv.dragviewtest.DragView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/frameLayout1">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="#000000" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="CheckBox"
android:textColor="#android:color/white" />
</com.lycatv.dragviewtest.DragView>
</com.lycatv.dragviewtest.MinimizableView>
The CheckBox does not work when you press on it. Instead it works when you press above it. By whatever amount it is offset from the top.
I won't pretend to understand everything your code is doing. However, I did notice something in onLayout that is almost certainly wrong. The code you posted is this:
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (isInEditMode() || firstLayoutPass) {
super.onLayout(changed, left, top, right, bottom);
mainViewInitialPosition = mainView.getTop();
verticalDragRange = getMeasuredHeight() - mainViewInitialPosition - getMinHeightPlusMargin() - getPaddingTop() - getPaddingBottom();
for (int i = 0; i < otherViews.size(); i++) {
initialPositions.add(otherViews.get(i).getTop());
}
firstLayoutPass = false;
} else if (isMainViewAtTop()) {
mainView.layout(left, mainViewInitialPosition, right, mainViewInitialPosition + mainViewOriginalHeight);
changeUnmovableViewAlpha(0);
setLayoutPositions(0, left, right, bottom, true);
} else {
setLayoutPositions(mainView.getTop() / (float) verticalDragRange, left, right, bottom, false);
}
}
The almost-certain error in this code is in your use of the layout method here:
mainView.layout(left, mainViewInitialPosition, right, mainViewInitialPosition + mainViewOriginalHeight);
You are using the parameter values left and right to layout your mainView (and the child views via setLayoutPositions). This is wrong. Keep in mind that left, top, right and bottom are the relative positions of your parent view (MinimizableView); they should not be used directly to layout your child views, as the child views are relative to MinimizableView, not to the parent of MinimizableView.
For example, when you layout mainView, the values you pass into layout() are interpreted as being relative to MinimizableView. This means the left offset should be 0 (plus padding), not left. Diddo for right. You layout call should look more like:
mainView.layout(0, 0, mainView.getMeasuredWidth(), mainView.getMeasuredHeight());
Note that the above does not account for padding.
I tried setting background color in my xml file in custom scroll view but it showed error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Alert dialog color is white i want slightly transparent!
having background color of the alert dialog to be #24000000(slightly transparent) in this small library taken from here:
https://github.com/wangjiegulu/WheelView
What changes are needed to accomplish that?
Custom scroll view:
/**
* Author: wangjie
* Email: tiantian.china.2#gmail.com
* Date: 7/1/14.
*/
public class WheelView extends ScrollView {
public static final String TAG = WheelView.class.getSimpleName();
public static class OnWheelViewListener {
public void onSelected(int selectedIndex, String item) {
}
}
private Context context;
// private ScrollView scrollView;
private LinearLayout views;
public WheelView(Context context) {
super(context);
init(context);
}
public WheelView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public WheelView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
// String[] items;
List<String> items;
private List<String> getItems() {
return items;
}
public void setItems(List<String> list) {
if (null == items) {
items = new ArrayList<String>();
}
items.clear();
items.addAll(list);
// 前面和后面补全
for (int i = 0; i < offset; i++) {
items.add(0, "");
items.add("");
}
initData();
}
public static final int OFF_SET_DEFAULT = 1;
int offset = OFF_SET_DEFAULT; // 偏移量(需要在最前面和最后面补全)
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
int displayItemCount; // 每页显示的数量
int selectedIndex = 1;
private void init(Context context) {
this.context = context;
// scrollView = ((ScrollView)this.getParent());
// Log.d(TAG, "scrollview: " + scrollView);
Log.d(TAG, "parent: " + this.getParent());
// this.setOrientation(VERTICAL);
this.setVerticalScrollBarEnabled(false);
views = new LinearLayout(context);
views.setOrientation(LinearLayout.VERTICAL);
this.addView(views);
scrollerTask = new Runnable() {
public void run() {
int newY = getScrollY();
if (initialY - newY == 0) { // stopped
final int remainder = initialY % itemHeight;
final int divided = initialY / itemHeight;
// Log.d(TAG, "initialY: " + initialY);
// Log.d(TAG, "remainder: " + remainder + ", divided: " + divided);
if (remainder == 0) {
selectedIndex = divided + offset;
onSeletedCallBack();
} else {
if (remainder > itemHeight / 2) {
WheelView.this.post(new Runnable() {
#Override
public void run() {
WheelView.this.smoothScrollTo(0, initialY - remainder + itemHeight);
selectedIndex = divided + offset + 1;
onSeletedCallBack();
}
});
} else {
WheelView.this.post(new Runnable() {
#Override
public void run() {
WheelView.this.smoothScrollTo(0, initialY - remainder);
selectedIndex = divided + offset;
onSeletedCallBack();
}
});
}
}
} else {
initialY = getScrollY();
WheelView.this.postDelayed(scrollerTask, newCheck);
}
}
};
}
int initialY;
Runnable scrollerTask;
int newCheck = 50;
public void startScrollerTask() {
initialY = getScrollY();
this.postDelayed(scrollerTask, newCheck);
}
private void initData() {
displayItemCount = offset * 2 + 1;
for (String item : items) {
views.addView(createView(item));
}
refreshItemView(0);
}
int itemHeight = 0;
private TextView createView(String item) {
TextView tv = new TextView(context);
tv.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tv.setSingleLine(true);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
tv.setText(item);
tv.setGravity(Gravity.CENTER);
int padding = dip2px(15);
tv.setPadding(padding, padding, padding, padding);
if (0 == itemHeight) {
itemHeight = getViewMeasuredHeight(tv);
Log.d(TAG, "itemHeight: " + itemHeight);
views.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight * displayItemCount));
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.getLayoutParams();
this.setLayoutParams(new LinearLayout.LayoutParams(lp.width, itemHeight * displayItemCount));
}
return tv;
}
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
// Log.d(TAG, "l: " + l + ", t: " + t + ", oldl: " + oldl + ", oldt: " + oldt);
// try {
// Field field = ScrollView.class.getDeclaredField("mScroller");
// field.setAccessible(true);
// OverScroller mScroller = (OverScroller) field.get(this);
//
//
// if(mScroller.isFinished()){
// Log.d(TAG, "isFinished...");
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
refreshItemView(t);
if (t > oldt) {
// Log.d(TAG, "向下滚动");
scrollDirection = SCROLL_DIRECTION_DOWN;
} else {
// Log.d(TAG, "向上滚动");
scrollDirection = SCROLL_DIRECTION_UP;
}
}
private void refreshItemView(int y) {
int position = y / itemHeight + offset;
int remainder = y % itemHeight;
int divided = y / itemHeight;
if (remainder == 0) {
position = divided + offset;
} else {
if (remainder > itemHeight / 2) {
position = divided + offset + 1;
}
// if(remainder > itemHeight / 2){
// if(scrollDirection == SCROLL_DIRECTION_DOWN){
// position = divided + offset;
// Log.d(TAG, ">down...position: " + position);
// }else if(scrollDirection == SCROLL_DIRECTION_UP){
// position = divided + offset + 1;
// Log.d(TAG, ">up...position: " + position);
// }
// }else{
//// position = y / itemHeight + offset;
// if(scrollDirection == SCROLL_DIRECTION_DOWN){
// position = divided + offset;
// Log.d(TAG, "<down...position: " + position);
// }else if(scrollDirection == SCROLL_DIRECTION_UP){
// position = divided + offset + 1;
// Log.d(TAG, "<up...position: " + position);
// }
// }
// }
// if(scrollDirection == SCROLL_DIRECTION_DOWN){
// position = divided + offset;
// }else if(scrollDirection == SCROLL_DIRECTION_UP){
// position = divided + offset + 1;
}
int childSize = views.getChildCount();
for (int i = 0; i < childSize; i++) {
TextView itemView = (TextView) views.getChildAt(i);
if (null == itemView) {
return;
}
if (position == i) {
itemView.setTextColor(Color.parseColor("#0288ce"));
} else {
itemView.setTextColor(Color.parseColor("#bbbbbb"));
}
}
}
/**
* 获取选中区域的边界
*/
int[] selectedAreaBorder;
private int[] obtainSelectedAreaBorder() {
if (null == selectedAreaBorder) {
selectedAreaBorder = new int[2];
selectedAreaBorder[0] = itemHeight * offset;
selectedAreaBorder[1] = itemHeight * (offset + 1);
}
return selectedAreaBorder;
}
private int scrollDirection = -1;
private static final int SCROLL_DIRECTION_UP = 0;
private static final int SCROLL_DIRECTION_DOWN = 1;
Paint paint;
int viewWidth;
#Override
public void setBackgroundDrawable(Drawable background) {
if (viewWidth == 0) {
viewWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
Log.d(TAG, "viewWidth: " + viewWidth);
}
if (null == paint) {
paint = new Paint();
paint.setColor(Color.parseColor("#83cde6"));
paint.setStrokeWidth(dip2px(1f));
}
background = new Drawable() {
#Override
public void draw(Canvas canvas) {
canvas.drawLine(viewWidth * 1 / 6, obtainSelectedAreaBorder()[0], viewWidth * 5 / 6, obtainSelectedAreaBorder()[0], paint);
canvas.drawLine(viewWidth * 1 / 6, obtainSelectedAreaBorder()[1], viewWidth * 5 / 6, obtainSelectedAreaBorder()[1], paint);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return 0;
}
};
super.setBackgroundDrawable(background);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.d(TAG, "w: " + w + ", h: " + h + ", oldw: " + oldw + ", oldh: " + oldh);
viewWidth = w;
setBackgroundDrawable(null);
}
/**
* 选中回调
*/
private void onSeletedCallBack() {
if (null != onWheelViewListener) {
onWheelViewListener.onSelected(selectedIndex, items.get(selectedIndex));
}
}
public void setSeletion(int position) {
final int p = position;
selectedIndex = p + offset;
this.post(new Runnable() {
#Override
public void run() {
WheelView.this.smoothScrollTo(0, p * itemHeight);
}
});
}
public String getSeletedItem() {
return items.get(selectedIndex);
}
public int getSeletedIndex() {
return selectedIndex - offset;
}
#Override
public void fling(int velocityY) {
super.fling(velocityY / 3);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP) {
startScrollerTask();
}
return super.onTouchEvent(ev);
}
private OnWheelViewListener onWheelViewListener;
public OnWheelViewListener getOnWheelViewListener() {
return onWheelViewListener;
}
public void setOnWheelViewListener(OnWheelViewListener onWheelViewListener) {
this.onWheelViewListener = onWheelViewListener;
}
private int dip2px(float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
private int getViewMeasuredHeight(View view) {
int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
view.measure(width, expandSpec);
return view.getMeasuredHeight();
}
}
Main activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String[] PLANETS = new String[]{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Uranus", "Neptune", "Pluto"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WheelView wva = (WheelView) findViewById(R.id.main_wv);
wva.setOffset(1);
wva.setItems(Arrays.asList(PLANETS));
wva.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
#Override
public void onSelected(int selectedIndex, String item) {
Log.d(TAG, "selectedIndex: " + selectedIndex + ", item: " + item);
}
});
findViewById(R.id.main_show_dialog_btn).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_show_dialog_btn:
View outerView = LayoutInflater.from(this).inflate(R.layout.wheel_view, null);
WheelView wv = (WheelView) outerView.findViewById(R.id.wheel_view_wv);
wv.setOffset(2);
wv.setItems(Arrays.asList(PLANETS));
wv.setSeletion(3);
wv.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
#Override
public void onSelected(int selectedIndex, String item) {
Log.d(TAG, "[Dialog]selectedIndex: " + selectedIndex + ", item: " + item);
}
});
new AlertDialog.Builder(this)
.setTitle("WheelView in Dialog")
.setView(outerView)
.setPositiveButton("OK", null)
.show();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am using ViewPageIndicator for developing a pager view with its indicator
MyCode
Activity
public class Pager extends Activity{
private MyPagerAdapter mAdapter;
private ViewPager mPager;
private CirclePageIndicator mIndicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager);
mAdapter=new MyPagerAdapter(getApplicationContext());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
MyPagerAdapter .java
public class MyPagerAdapter extends PagerAdapter{
protected static final String[] CONTENT = new String[] { "This", "Is", "A", "Test", "Demo","Sample","Example" ,
"Application","To","Study","And","Implement","Page-Viewer","And","Page-Indicator","For","News"};
private Context ctx;
private int mCount = CONTENT.length;
public MyPagerAdapter(Context ctx){
this.ctx = ctx;
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object instantiateItem(View collection, int position) {
TextView view = new TextView(ctx);
view.setGravity(Gravity.CENTER);
view.setTextSize(20 );
view.setPadding(20, 20, 20, 20);
view.setText(CONTENT[position]);
((ViewPager)collection).addView(view);
return view;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
#Override
public void startUpdate(View arg0) {
}
#Override
public void finishUpdate(View arg0) {
}
}
I modified CirclePageIndicator.java created by JakeWharton to my use
public class CirclePageIndicator extends View implements PageIndicator {
private static final int INVALID_POINTER = -1;
private float mRadius;
private final Paint mPaintPageFill = new Paint(ANTI_ALIAS_FLAG);
private final Paint mPaintStroke = new Paint(ANTI_ALIAS_FLAG);
private final Paint mPaintFill = new Paint(ANTI_ALIAS_FLAG);
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mListener;
private int mCurrentPage;
private float mPageOffset;
private int mScrollState;
private int mOrientation;
private boolean mCentered;
private int mTouchSlop;
private float mLastMotionX = -1;
private int mActivePointerId = INVALID_POINTER;
private boolean mIsDragging;
int mCount = 0;
public CirclePageIndicator(Context context) {
this(context, null);
}
public CirclePageIndicator(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.vpiCirclePageIndicatorStyle);
}
public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode()) return;
//Load defaults from resources
final Resources res = getResources();
final int defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color);
final int defaultFillColor = res.getColor(R.color.default_circle_indicator_fill_color);
final int defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation);
final int defaultStrokeColor = res.getColor(R.color.default_circle_indicator_stroke_color);
final float defaultStrokeWidth = res.getDimension(R.dimen.default_circle_indicator_stroke_width);
final float defaultRadius = res.getDimension(R.dimen.default_circle_indicator_radius);
final boolean defaultCentered = res.getBoolean(R.bool.default_circle_indicator_centered);
//Retrieve styles attributes
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, 0);
mCentered = a.getBoolean(R.styleable.CirclePageIndicator_centered, defaultCentered);
mOrientation = a.getInt(R.styleable.CirclePageIndicator_android_orientation, defaultOrientation);
mPaintPageFill.setStyle(Style.FILL);
mPaintPageFill.setColor(a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor));
mPaintStroke.setStyle(Style.STROKE);
mPaintStroke.setColor(a.getColor(R.styleable.CirclePageIndicator_strokeColor, defaultStrokeColor));
mPaintStroke.setStrokeWidth(a.getDimension(R.styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth));
mPaintFill.setStyle(Style.FILL);
mPaintFill.setColor(a.getColor(R.styleable.CirclePageIndicator_fillColor, defaultFillColor));
mRadius = a.getDimension(R.styleable.CirclePageIndicator_radius, defaultRadius);
Drawable background = a.getDrawable(R.styleable.CirclePageIndicator_android_background);
if (background != null) {
setBackgroundDrawable(background);
}
a.recycle();
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
}
public void setCentered(boolean centered) {
mCentered = centered;
notifyDataSetChanged();
}
public boolean isCentered() {
return mCentered;
}
public void setFillColor(int fillColor) {
mPaintFill.setColor(fillColor);
notifyDataSetChanged();
}
public int getFillColor() {
return mPaintFill.getColor();
}
public void setOrientation(int orientation) {
switch (orientation) {
case HORIZONTAL:
case VERTICAL:
mOrientation = orientation;
requestLayout();
break;
default:
throw new IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.");
}
}
public int getOrientation() {
return mOrientation;
}
public void setStrokeColor(int strokeColor) {
mPaintStroke.setColor(strokeColor);
notifyDataSetChanged();
}
public int getStrokeColor() {
return mPaintStroke.getColor();
}
public void setStrokeWidth(float strokeWidth) {
mPaintStroke.setStrokeWidth(strokeWidth);
notifyDataSetChanged();
}
public float getStrokeWidth() {
return mPaintStroke.getStrokeWidth();
}
public void setRadius(float radius) {
mRadius = radius;
notifyDataSetChanged();
}
public float getRadius() {
return mRadius;
}
boolean greaterThanFive = false;
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mViewPager == null) {
return;
}
//if(!greaterThanFive){
mCount = mViewPager.getAdapter().getCount();
// }
int condition=5;
if(mCurrentPage>4)
condition=2;
if (mCount == 0) {
return;
}
if (mCurrentPage >= mCount) {
setCurrentItem(mCount-1);
return;
}
int longSize;
int longPaddingBefore;
int longPaddingAfter;
int shortPaddingBefore;
if (mOrientation == HORIZONTAL) {
longSize = getWidth();
longPaddingBefore = getPaddingLeft();
longPaddingAfter = getPaddingRight();
shortPaddingBefore = getPaddingTop();
} else {
longSize = getHeight();
longPaddingBefore = getPaddingTop();
longPaddingAfter = getPaddingBottom();
shortPaddingBefore = getPaddingLeft();
}
final float threeRadius = mRadius * 3;
final float shortOffset = shortPaddingBefore + mRadius;
float longOffset = longPaddingBefore + mRadius;
if (mCentered) {
longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((condition * threeRadius) / 2.0f);
}
float dX;
float dY;
float pageFillRadius = mRadius;
if (mPaintStroke.getStrokeWidth() > 0) {
pageFillRadius -= mPaintStroke.getStrokeWidth() / 2.0f;
}
//Draw stroked circles
for (int iLoop = 0; iLoop < condition; iLoop++) {
float drawLong = longOffset + (iLoop * threeRadius);
if (mOrientation == HORIZONTAL) {
dX = drawLong;
dY = shortOffset;
} else {
dX = shortOffset;
dY = drawLong;
}
// Only paint fill if not completely transparent
if (mPaintPageFill.getAlpha() > 0) {
canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill);
}
// Only paint stroke if a stroke width was non-zero
if (pageFillRadius != mRadius) {
canvas.drawCircle(dX, dY, mRadius, mPaintStroke);
}
}
//Draw the filled circle according to the current scroll
float cx= mCurrentPage* threeRadius;
cx += mPageOffset * threeRadius;
if (mOrientation == HORIZONTAL) {
dX = longOffset + cx;
dY = shortOffset;
} else {
dX = shortOffset;
dY = longOffset + cx;
}
canvas.drawCircle(dX, dY, mRadius, mPaintFill);
}
public boolean onTouchEvent(android.view.MotionEvent ev) {
if (super.onTouchEvent(ev)) {
return true;
}
if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
return false;
}
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mLastMotionX = ev.getX();
break;
case MotionEvent.ACTION_MOVE: {
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = x - mLastMotionX;
if (!mIsDragging) {
if (Math.abs(deltaX) > mTouchSlop) {
mIsDragging = true;
}
}
if (mIsDragging) {
mLastMotionX = x;
if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
mViewPager.fakeDragBy(deltaX);
}
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (!mIsDragging) {
final int count = mViewPager.getAdapter().getCount();
final int width = getWidth();
final float halfWidth = width / 2f;
final float sixthWidth = width / 6f;
if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
if (action != MotionEvent.ACTION_CANCEL) {
mViewPager.setCurrentItem(mCurrentPage - 1);
}
return true;
} else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
if (action != MotionEvent.ACTION_CANCEL) {
mViewPager.setCurrentItem(mCurrentPage + 1);
}
return true;
}
}
mIsDragging = false;
mActivePointerId = INVALID_POINTER;
if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mLastMotionX = MotionEventCompat.getX(ev, index);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
return true;
}
#Override
public void setViewPager(ViewPager view) {
if (mViewPager == view) {
return;
}
if (mViewPager != null) {
mViewPager.setOnPageChangeListener(null);
}
if (view.getAdapter() == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
mViewPager = view;
mViewPager.setOnPageChangeListener(this);
notifyDataSetChanged();
}
#Override
public void setViewPager(ViewPager view, int initialPosition) {
setViewPager(view);
setCurrentItem(initialPosition);
}
#Override
public void setCurrentItem(int item) {
if (mViewPager == null) {
throw new IllegalStateException("ViewPager has not been bound.");
}
mViewPager.setCurrentItem(item);
mCurrentPage = item;
notifyDataSetChanged();
}
#Override
public void notifyDataSetChanged() {
invalidate();
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mListener != null) {
mListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
mCurrentPage = position;
mPageOffset = positionOffset;
notifyDataSetChanged();
if (mListener != null) {
mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
#Override
public void onPageSelected(int position) {
/*if(position>4){
mCount=2;
greaterThanFive=true;
mCurrentPage = position;
notifyDataSetChanged();
return;
}*/
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mCurrentPage = position;
notifyDataSetChanged();
}
if (mListener != null) {
mListener.onPageSelected(position);
}
}
#Override
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mListener = listener;
}
public void onExcessPage(){
}
/*
* (non-Javadoc)
*
* #see android.view.View#onMeasure(int, int)
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == HORIZONTAL) {
setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
} else {
setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec));
}
}
/**
* Determines the width of this view
*
* #param measureSpec
* A measureSpec packed into an int
* #return The width of the view, honoring constraints from measureSpec
*/
private int measureLong(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
//We were told how big to be
result = specSize;
} else {
//Calculate the width according the views count
final int count = mViewPager.getAdapter().getCount();
result = (int)(getPaddingLeft() + getPaddingRight()
+ (count * 2 * mRadius) + (count - 1) * mRadius + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
/**
* Determines the height of this view
*
* #param measureSpec
* A measureSpec packed into an int
* #return The height of the view, honoring constraints from measureSpec
*/
private int measureShort(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
//We were told how big to be
result = specSize;
} else {
//Measure the height
result = (int)(2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState)state;
super.onRestoreInstanceState(savedState.getSuperState());
mCurrentPage = savedState.currentPage;
requestLayout();
}
#Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentPage = mCurrentPage;
return savedState;
}
static class SavedState extends BaseSavedState {
int currentPage;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentPage = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPage);
}
#SuppressWarnings("UnusedDeclaration")
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
#Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
#Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
PageIndicator .java
public interface PageIndicator extends ViewPager.OnPageChangeListener {
void setViewPager(ViewPager view);
void setViewPager(ViewPager view, int initialPosition);
void setCurrentItem(int item);
void setOnPageChangeListener(ViewPager.OnPageChangeListener listener);
void notifyDataSetChanged();
}
My layout XML is
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_play"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="play" />
<Button
android:id="#+id/btn_pause"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="pause" />
<Button
android:id="#+id/btn_stop"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="stop" />
</LinearLayout>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<com.example.demopager.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip" />
</LinearLayout>
Here you can see there is more than 10 pages in my pager .The thing i want to do id when i reach the 6th page i want to redraw the page indicator to 2 dots with out selection.
For first 5 Page changes it should be like this
After when i move to next page(page no >5) i want to avoid the selection of indicator and show only two indicators
Hope you understand what's my need (My English is not that good)..
So Please suggest me how can achieve this
Courtesy :Patrik Åkerfeldt & Jake Wharton
In details, I am looking for an example exactly like below image. I got a good example in this link https://github.com/woozzu/IndexableListView. Its works fine as my requirement.But problem when i implementing to my project it is showing error in list view. below is my code plz help me. i am new to this topic. Thank you in advance!
looking for:
here is my code below plz say my mistake..
MainActivity .java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener {
private ListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
EfficientAdapter2 objectAdapter1;
int textlength=0;
private CheckBox checkStat, checkRoutine, checkTat;
private GestureDetector mGestureDetector;
private ArrayList<CountriesList> elements;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan"," txtScanResult ");
//Arrays.sort(CountriesList.name);
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this, QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed", Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT", Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE", Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency", Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
objectAdapter = new EfficientAdapter(this, elements );
listView.setAdapter(objectAdapter);
Button refreshButton= (Button)findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
objectAdapter1 = new EfficientAdapter2(MainActivity.this);
// objectAdapter = new EfficientAdapter(MainActivity.this);// adapter with new data
listView.setAdapter(objectAdapter1);
Log.i("notifyDataSetChanged", "data updated");
objectAdapter1.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.java
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private AlphabetIndexer alphaIndexer;
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context, ArrayList<CountriesList> elements) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
public int getCount() {
return CountriesList.name.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.name);
holder.text2 = (TextView) convertView
.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView
.findViewById(R.id.date);
holder.text4 = (TextView) convertView
.findViewById(R.id.age);
holder.text5 = (TextView) convertView
.findViewById(R.id.gender);
holder.text6 = (TextView) convertView
.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView
.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView
.findViewById(R.id.bedno);
holder.btnList = (Button)convertView.findViewById(R.id.listbutton);
// holder.btnList.setOnClickListener(this);
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(CountriesList.name[position]);
holder.text2.setText(CountriesList.mrn[position]);
holder.text3.setText(CountriesList.actualstart[position]);
holder.text4.setText(CountriesList.age[position]);
holder.text5.setText(CountriesList.gender[position]);
holder.text6.setText(CountriesList.wardNo[position]);
holder.text7.setText(CountriesList.roomNo[position]);
holder.text8.setText(CountriesList.bedNo[position]);
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public int getPositionForSection(int section) {
// If there is no item for current section, previous section will be selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
// if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(k)))
return j;
}
} else {
// if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
IndexableListView.java
public class IndexableListView extends ListView {
private boolean mIsFastScrollEnabled = false;
private IndexScroller mScroller = null;
private GestureDetector mGestureDetector = null;
public IndexableListView(Context context) {
super(context);
}
public IndexableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IndexableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean isFastScrollEnabled() {
return mIsFastScrollEnabled;
}
#Override
public void setFastScrollEnabled(boolean enabled) {
mIsFastScrollEnabled = enabled;
if (mIsFastScrollEnabled) {
if (mScroller == null)
mScroller = new IndexScroller(getContext(), this);
} else {
if (mScroller != null) {
mScroller.hide();
mScroller = null;
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
// Overlay index bar
if (mScroller != null)
mScroller.draw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Intercept ListView's touch event
if (mScroller != null && mScroller.onTouchEvent(ev))
return true;
if (mGestureDetector == null) {
mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// If fling happens, index bar shows
mScroller.show();
return super.onFling(e1, e2, velocityX, velocityY);
}
});
}
mGestureDetector.onTouchEvent(ev);
return super.onTouchEvent(ev);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
if (mScroller != null)
mScroller.setAdapter(adapter);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mScroller != null)
mScroller.onSizeChanged(w, h, oldw, oldh);
}
}
StringMatcher.java
public class StringMatcher {
public static boolean match(String value, String keyword) {
if (value == null || keyword == null)
return false;
if (keyword.length() > value.length())
return false;
int i = 0, j = 0;
do {
if (isKorean(value.charAt(i)) && isInitialSound(keyword.charAt(j))) {
} else {
if (keyword.charAt(j) == value.charAt(i)) {
i++;
j++;
} else if (j > 0)
break;
else
i++;
}
} while (i < value.length() && j < keyword.length());
return (j == keyword.length())? true : false;
}
private static boolean isKorean(char c) {
return false;
}
private static boolean isInitialSound(char c) {
return false;
}
}
IndexScroller.java
public class IndexScroller {
private static final int STATE_HIDDEN = 0;
private static final int STATE_SHOWING = 1;
private static final int STATE_SHOWN = 2;
private static final int STATE_HIDING = 3;
public IndexScroller(Context context, ListView lv) {
mDensity = context.getResources().getDisplayMetrics().density;
mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
mListView = lv;
setAdapter(mListView.getAdapter());
mIndexbarWidth = 20 * mDensity;
mIndexbarMargin = 10 * mDensity;
mPreviewPadding = 5 * mDensity;
}
public void draw(Canvas canvas) {
if (mState == STATE_HIDDEN)
return;
// mAlphaRate determines the rate of opacity
Paint indexbarPaint = new Paint();
indexbarPaint.setColor(Color.BLACK);
indexbarPaint.setAlpha((int) (64 * mAlphaRate));
indexbarPaint.setAntiAlias(true);
canvas.drawRoundRect(mIndexbarRect, 5 * mDensity, 5 * mDensity, indexbarPaint);
if (mSections != null && mSections.length > 0) {
// Preview is shown when mCurrentSection is set
if (mCurrentSection >= 0) {
Paint previewPaint = new Paint();
previewPaint.setColor(Color.BLACK);
previewPaint.setAlpha(96);
previewPaint.setAntiAlias(true);
previewPaint.setShadowLayer(3, 0, 0, Color.argb(64, 0, 0, 0));
Paint previewTextPaint = new Paint();
previewTextPaint.setColor(Color.WHITE);
previewTextPaint.setAntiAlias(true);
previewTextPaint.setTextSize(50 * mScaledDensity);
float previewTextWidth = previewTextPaint.measureText(mSections[mCurrentSection]);
float previewSize = 2 * mPreviewPadding + previewTextPaint.descent() - previewTextPaint.ascent();
RectF previewRect = new RectF((mListViewWidth - previewSize) / 2
, (mListViewHeight - previewSize) / 2
, (mListViewWidth - previewSize) / 2 + previewSize
, (mListViewHeight - previewSize) / 2 + previewSize);
canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
canvas.drawText(mSections[mCurrentSection], previewRect.left + (previewSize - previewTextWidth) / 2 - 1
, previewRect.top + mPreviewPadding - previewTextPaint.ascent() + 1, previewTextPaint);
}
Paint indexPaint = new Paint();
indexPaint.setColor(Color.WHITE);
indexPaint.setAlpha((int) (255 * mAlphaRate));
indexPaint.setAntiAlias(true);
indexPaint.setTextSize(12 * mScaledDensity);
float sectionHeight = (mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length;
float paddingTop = (sectionHeight - (indexPaint.descent() - indexPaint.ascent())) / 2;
for (int i = 0; i < mSections.length; i++) {
float paddingLeft = (mIndexbarWidth - indexPaint.measureText(mSections[i])) / 2;
canvas.drawText(mSections[i], mIndexbarRect.left + paddingLeft
, mIndexbarRect.top + mIndexbarMargin + sectionHeight * i + paddingTop - indexPaint.ascent(), indexPaint);
}
}
}
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// If down event occurs inside index bar region, start indexing
if (mState != STATE_HIDDEN && contains(ev.getX(), ev.getY())) {
setState(STATE_SHOWN);
// It demonstrates that the motion event started from index bar
mIsIndexing = true;
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
return true;
}
break;
case MotionEvent.ACTION_MOVE:
if (mIsIndexing) {
// If this event moves inside index bar
if (contains(ev.getX(), ev.getY())) {
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
}
return true;
}
break;
case MotionEvent.ACTION_UP:
if (mIsIndexing) {
mIsIndexing = false;
mCurrentSection = -1;
}
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
break;
}
return false;
}
public void onSizeChanged(int w, int h, int oldw, int oldh) {
mListViewWidth = w;
mListViewHeight = h;
mIndexbarRect = new RectF(w - mIndexbarMargin - mIndexbarWidth
, mIndexbarMargin
, w - mIndexbarMargin
, h - mIndexbarMargin);
}
public void show() {
if (mState == STATE_HIDDEN)
setState(STATE_SHOWING);
else if (mState == STATE_HIDING)
setState(STATE_HIDING);
}
public void hide() {
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
}
public void setAdapter(Adapter adapter) {
if (adapter instanceof SectionIndexer) {
mIndexer = (SectionIndexer) adapter;
mSections = (String[]) mIndexer.getSections();
}
}
private void setState(int state) {
if (state < STATE_HIDDEN || state > STATE_HIDING)
return;
mState = state;
switch (mState) {
case STATE_HIDDEN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_SHOWING:
// Start to fade in
mAlphaRate = 0;
fade(0);
break;
case STATE_SHOWN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_HIDING:
// Start to fade out after three seconds
mAlphaRate = 1;
fade(3000);
break;
}
}
private boolean contains(float x, float y) {
// Determine if the point is in index bar region, which includes the right margin of the bar
return (x >= mIndexbarRect.left && y >= mIndexbarRect.top && y <= mIndexbarRect.top + mIndexbarRect.height());
}
private int getSectionByPoint(float y) {
if (mSections == null || mSections.length == 0)
return 0;
if (y < mIndexbarRect.top + mIndexbarMargin)
return 0;
if (y >= mIndexbarRect.top + mIndexbarRect.height() - mIndexbarMargin)
return mSections.length - 1;
return (int) ((y - mIndexbarRect.top - mIndexbarMargin) / ((mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length));
}
private void fade(long delay) {
mHandler.removeMessages(0);
mHandler.sendEmptyMessageAtTime(0, SystemClock.uptimeMillis() + delay);
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (mState) {
case STATE_SHOWING:
// Fade in effect
mAlphaRate += (1 - mAlphaRate) * 0.2;
if (mAlphaRate > 0.9) {
mAlphaRate = 1;
setState(STATE_SHOWN);
}
mListView.invalidate();
fade(10);
break;
case STATE_SHOWN:
// If no action, hide automatically
setState(STATE_HIDING);
break;
case STATE_HIDING:
// Fade out effect
mAlphaRate -= mAlphaRate * 0.2;
if (mAlphaRate < 0.1) {
mAlphaRate = 0;
setState(STATE_HIDDEN);
}
mListView.invalidate();
fade(10);
break;
}
}
};
}
if i add this it works code in mainactivity
listView = (ListView) findViewById(R.id.homelistView);
your are using a custom ListView class, com.woozzu.android.widget.IndexableListView
You have to replace your "ListView " in layout file to a "com.woozzu.android.widget.IndexableListView"
Change your Layout to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#ff3344"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffffff"
android:layout_alignTop="#+id/scrollView1"
android:layout_toRightOf="#+id/scrollView1" >
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The solution Suggested by #Anis is the only working solution I found. In addition to that, If you want Click listeners to components on your List View Items, you have to update the Code as mentioned here, https://github.com/denley/IndexableListView/commit/18210a54487ba079bb332fafec709e2de26883db