I have a list view where every item is a MPAndroidChart. The problem is that on the chart i set some gestures but when i try to perform these the list view intercept the gesture and perform the scroll.
Now i want to maintain the scroll of the list view but i want to perform the gesture on chart, how this is possible?
Also disable the scroll is useless because the list view anyway intercept the touch event and sto to perform the gesture on chart.
So what i want to do is to stop the list view to intercept the chart gesture but maintain the scroll of the list view
Class of the list view
public class ListViewMultiChartActivity extends DemoBase {
public static Button check_button, close_button;
public static LineChartItem chart;
public static ScatterChartItem chart2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_listview_chart);
check_button = (Button) findViewById(R.id.button);
close_button = (Button) findViewById(R.id.button2);
check_button.setVisibility(View.INVISIBLE);
close_button.setVisibility(View.INVISIBLE);
ListView lv = (ListView) findViewById(R.id.listView1);
ArrayList<ChartItem> list = new ArrayList<ChartItem>();
list.add(new LineChartItem(generateDataLine(0), getApplicationContext()));
list.add(new ScatterChartItem(generateDataScatter(1), getApplicationContext()));
ChartDataAdapter cda = new ChartDataAdapter(getApplicationContext(), list);
lv.setAdapter(cda);
chart = (LineChartItem) list.get(0);
chart2 = (ScatterChartItem) list.get(1);
check_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (chart.mChart.end_selection || chart2.mChart.end_selection) {
Highlight[] high;
if (chart.mChart.end_selection) {
high = chart.mChart.getHighlighted();
} else {
high = chart2.mChart.getHighlighted();
}
ArrayList<Entry> position;
ArrayList<Entry> position2;
LineDataSet d;
ScatterDataSet d2;
int i;
int j = 0;
int size = chart.mChart.getData().getDataSetCount();
while (j < size) {
i = 0;
position = new ArrayList<>();
position2 = new ArrayList<>();
while (i < high.length) {
int k = 0;
while (k < chart.mChart.getData().getDataSetByIndex(j).getEntryCount()) {
if (high[i].getX() == chart.mChart.getData().getDataSetByIndex(j).getEntryForIndex(k).getX() && j == high[i].getDataSetIndex()) {
position.add(chart.mChart.getData().getDataSetByIndex(j).getEntryForIndex(k));
position2.add(chart.mChart.getData().getDataSetByIndex(j).getEntryForIndex(k));
}
k++;
}
i++;
}
if (position.size() != 0) {
d = new LineDataSet(position, "Data" + j);
d.setLineWidth(2.5f);
d.setCircleRadius(4f);
int color = mColors[j % mColors.length];
d.setColor(color);
d.setCircleColor(color);
chart.mChart.getData().addDataSet(d);
d2 = new ScatterDataSet(position2, "Data" + j);
d2.setColor(color);
chart2.mChart.getData().addDataSet(d2);
}
j++;
}
i = 0;
while (i < size) {
chart.mChart.getData().removeDataSet(0);
chart2.mChart.getData().removeDataSet(0);
i++;
}
Highlight[] highvoid = new Highlight[0];
chart.mChart.highlightValues(highvoid);
chart2.mChart.highlightValues(highvoid);
chart.mChart.invalidate();
chart2.mChart.invalidate();
check_button.setVisibility(View.INVISIBLE);
close_button.setVisibility(View.INVISIBLE);
}
}
});
close_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (chart.mChart.end_selection || chart2.mChart.end_selection) {
Highlight[] high;
if (chart.mChart.end_selection) {
high = chart.mChart.getHighlighted();
} else {
high = chart2.mChart.getHighlighted();
}
int i = 0;
int j = 0;
while (i < high.length) {
j = 0;
while (j < chart.mChart.getData().getDataSetCount()) {
int k = 0;
while (k < chart.mChart.getData().getDataSetByIndex(j).getEntryCount()) {
if (high[i].getX() == chart.mChart.getData().getDataSetByIndex(j).getEntryForIndex(k).getX() && j == high[i].getDataSetIndex()) {
chart.mChart.getData().getDataSetByIndex(j).removeEntry(k);
chart2.mChart.getData().getDataSetByIndex(j).removeEntry(k);
}
k++;
}
j++;
}
i++;
}
Highlight[] highvoid = new Highlight[0];
chart.mChart.highlightValues(highvoid);
chart2.mChart.highlightValues(highvoid);
chart.mChart.invalidate();
chart2.mChart.invalidate();
check_button.setVisibility(View.INVISIBLE);
close_button.setVisibility(View.INVISIBLE);
}
}
});
}
/**
* adapter that supports 3 different item types
*/
private class ChartDataAdapter extends ArrayAdapter<ChartItem> {
public ChartDataAdapter(Context context, List<ChartItem> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getItem(position).getView(position, convertView, getContext());
}
#Override
public int getItemViewType(int position) {
// return the views type
return getItem(position).getItemType();
}
#Override
public int getViewTypeCount() {
return 3; // we have 3 different item-types
}
}
/**
* generates a random ChartData object with just one DataSet
*
* #return
*/
private LineData generateDataLine(int cnt) {
ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
ArrayList<Entry> values = new ArrayList<>();
for (int z = 0; z < 3; z++) {
values = new ArrayList<Entry>();
for (int i = 0; i < 20; i++) {
double val = (Math.random() * 100) + 3;
values.add(new Entry(i, (float) val));
}
LineDataSet d = new LineDataSet(values, "DataSet" + z);
d.setLineWidth(2.5f);
d.setCircleRadius(4f);
int color = mColors[z % mColors.length];
d.setColor(color);
d.setCircleColor(color);
dataSets.add(d);
}
LineData data = new LineData(dataSets);
return data;
}
/**
* generates a random ChartData object with just one DataSet
*
* #return
*/
private ScatterData generateDataScatter(int cnt) {
ArrayList<IScatterDataSet> dataSets = new ArrayList<IScatterDataSet>();
ArrayList<Entry> values = new ArrayList<>();
for (int z = 0; z < 3; z++) {
values = new ArrayList<Entry>();
for (int i = 0; i < 20; i++) {
double val = (Math.random() * 100) + 3;
values.add(new Entry(i, (float) val));
}
ScatterDataSet d = new ScatterDataSet(values, "DataSet" + z);
int color = mColors[z % mColors.length];
d.setColor(color);
dataSets.add(d);
}
ScatterData data = new ScatterData(dataSets);
return data;
}
private int[] mColors = new int[]{
ColorTemplate.VORDIPLOM_COLORS[0],
ColorTemplate.VORDIPLOM_COLORS[1],
ColorTemplate.VORDIPLOM_COLORS[2]
};
}
Abstact of the item of list view
public abstract class ChartItem {
protected static final int TYPE_BARCHART = 0;
protected static final int TYPE_LINECHART = 1;
protected static final int TYPE_PIECHART = 2;
protected static final int TYPE_SCATTERCHART = 3;
protected ChartData<?> mChartData;
public ChartItem(ChartData<?> cd) {
this.mChartData = cd;
}
public abstract int getItemType();
public abstract View getView(int position, View convertView, Context c);
}
Implementation of one of item of list view
public class ScatterChartItem extends ChartItem implements OnChartValueSelectedListener {
private Typeface mTf;
public ScatterChart mChart;
public ScatterChartItem(ChartData<?> cd, Context c) {
super(cd);
mTf = Typeface.createFromAsset(c.getAssets(), "OpenSans-Regular.ttf");
}
#Override
public int getItemType() {
return TYPE_SCATTERCHART;
}
#Override
public View getView(int position, View convertView, Context c) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(c).inflate(
R.layout.list_item_scatterchart, null);
holder.chart = (ScatterChart) convertView.findViewById(R.id.chart);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// apply styling
// holder.chart.setValueTypeface(mTf);
holder.chart.setDescription("");
holder.chart.setDrawGridBackground(false);
XAxis xAxis = holder.chart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTTOM);
xAxis.setTypeface(mTf);
xAxis.setDrawGridLines(false);
xAxis.setDrawAxisLine(true);
YAxis leftAxis = holder.chart.getAxisLeft();
leftAxis.setTypeface(mTf);
leftAxis.setLabelCount(5, false);
leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
YAxis rightAxis = holder.chart.getAxisRight();
rightAxis.setTypeface(mTf);
rightAxis.setLabelCount(5, false);
rightAxis.setDrawGridLines(false);
rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
// set data
holder.chart.setData((ScatterData) mChartData);
// do not forget to refresh the chart
// holder.chart.invalidate();
holder.chart.animateX(750);
holder.chart.setOnChartValueSelectedListener(this);
mChart=holder.chart;
return convertView;
}
#Override
public void onValueSelected(Entry e, Highlight h) {
}
#Override
public void onNothingSelected() {
}
#Override
public void onMultipleValueSelected() {
if (mChart.end_selection) {
Highlight[] high= mChart.getHighlighted();
ListViewMultiChartActivity.chart.mChart.highlightValues(high);
ListViewMultiChartActivity.check_button.setVisibility(View.VISIBLE);
ListViewMultiChartActivity.close_button.setVisibility(View.VISIBLE);
}else{
ListViewMultiChartActivity.check_button.setVisibility(View.INVISIBLE);
ListViewMultiChartActivity.close_button.setVisibility(View.INVISIBLE);
}
}
private static class ViewHolder {
ScatterChart chart;
}
}
I use the MPAndroidChart, here there is the class where i set the gesture of the chart
Related
Auto Scrolling is issue & also move to some specific position using code is difficult.
I am making two recyclerView dependent to each other with the Horizontal Scroll and center selection.
So my problem is using the method of Notifydatasetchanged and reseting recyclerView postion to 0 and it's scrolling selection range because it's returning wrong index...
When i want to get center selection index after changing data.
I am using below example to achieve this with some edits.
Get center visible item of RecycleView when scrolling
I need to change the data on scroll of First recyclerView Adapter to second recyclerView Adapter with data change.
But scrollview set the position in first position
I tried the notifyItemRangeChanged(int, int)
notifyItemRangeInserted(int, int) methods...
Detail Explanation : I am changing the type and reset the value of Look scrollview. I need to change the selected position of bottom scrollview. Specially I can't get the center position by changing data. Means I if i am notifying the adapter than index will remain as it is. I need to do work it like normal adapter after reset data.
Thanks in advance.
public void getRecyclerview_Type() {
final RecyclerView recyclerView_Type = (RecyclerView) findViewById(R.id.recycleView);
if (recyclerView_Type != null) {
recyclerView_Type.postDelayed(new Runnable() {
#Override
public void run() {
setTypeValue();
}
}, 300);
recyclerView_Type.postDelayed(new Runnable() {
#Override
public void run() {
// recyclerView_Type.smoothScrollToPosition(Type_Adapter.getItemCount() - 1);
setTypeValue();
}
}, 5000);
}
ViewTreeObserver treeObserver = recyclerView_Type.getViewTreeObserver();
treeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
recyclerView_Type.getViewTreeObserver().removeOnPreDrawListener(this);
finalWidthDate = recyclerView_Type.getMeasuredWidth();
itemWidthDate = getResources().getDimension(R.dimen.item_dob_width_padding);
paddingDate = (finalWidthDate - itemWidthDate) / 2;
firstItemWidthDate = paddingDate;
allPixelsDate = 0;
final LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getApplicationContext());
dateLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView_Type.setLayoutManager(dateLayoutManager);
recyclerView_Type.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
synchronized (this) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
calculatePositionAndScroll_Type(recyclerView);
}
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
allPixelsDate += dx;
}
});
if (mTypeBeanArrayList == null) {
mTypeBeanArrayList = new ArrayList<>();
}
getMedicationType();
Type_Adapter = new Medication_Type_RecyclerAdapter(Add_Reminder_medicationlook_Activity.this, mTypeBeanArrayList, (int) firstItemWidthDate);
recyclerView_Type.setAdapter(Type_Adapter);
Type_Adapter.setSelecteditem(Type_Adapter.getItemCount() - 1);
return true;
}
});
}
private void getMedicationType() {
for (int i = 0; i < mTypeBeanArrayList.size(); i++) {
Medication_TypeBean medication_typeBean = mTypeBeanArrayList.get(i);
Log.print("Image name :" +medication_typeBean.getType_image_name());
if (i == 0 || i == (mTypeBeanArrayList.size() - 1)) {
medication_typeBean.setType(VIEW_TYPE_PADDING);
} else {
medication_typeBean.setType(VIEW_TYPE_ITEM);
}
mTypeBeanArrayList.set(i, medication_typeBean);
}
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void calculatePositionAndScroll_Type(RecyclerView recyclerView) {
int expectedPositionDate = Math.round((allPixelsDate + paddingDate - firstItemWidthDate) / itemWidthDate);
if (expectedPositionDate == -1) {
expectedPositionDate = 0;
} else if (expectedPositionDate >= recyclerView.getAdapter().getItemCount() - 2) {
expectedPositionDate--;
}
scrollListToPosition_Type(recyclerView, expectedPositionDate);
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void scrollListToPosition_Type(RecyclerView recyclerView, int expectedPositionDate) {
float targetScrollPosDate = expectedPositionDate * itemWidthDate + firstItemWidthDate - paddingDate;
float missingPxDate = targetScrollPosDate - allPixelsDate;
if (missingPxDate != 0) {
recyclerView.smoothScrollBy((int) missingPxDate, 0);
}
setTypeValue();
}
private void setTypeValue() {
int expectedPositionDateColor = Math.round((allPixelsDate + paddingDate - firstItemWidthDate) / itemWidthDate);
int setColorDate = expectedPositionDateColor + 1;
Type_Adapter.setSelecteditem(setColorDate);
mTxt_type_name.setText(mTypeBeanArrayList.get(setColorDate).getMedication_type_name());
mSELECTED_TYPE_ID = setColorDate;
//NotifyLookChangetoType(setColorDate);
}
//Type Adapter
public class Medication_Type_RecyclerAdapter extends RecyclerView.Adapter<Medication_Type_RecyclerAdapter.ViewHolder> {
private ArrayList<Medication_TypeBean> medication_typeBeanArrayList;
private static final int VIEW_TYPE_PADDING = 1;
private static final int VIEW_TYPE_ITEM = 2;
private int paddingWidthDate = 0;
private Context mContext;
private int selectedItem = -1;
public Medication_Type_RecyclerAdapter(Context context, ArrayList<Medication_TypeBean> dateData, int paddingWidthDate) {
this.medication_typeBeanArrayList = dateData;
this.paddingWidthDate = paddingWidthDate;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_medication_type,
parent, false);
return new ViewHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_medication_type,
parent, false);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
layoutParams.width = paddingWidthDate;
view.setLayoutParams(layoutParams);
return new ViewHolder(view);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Medication_TypeBean medication_typeBean = mTypeBeanArrayList.get(position);
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
// holder.mTxt_Type.setText(medication_typeBean.getMedication_type_name());
//holder.mTxt_Type.setVisibility(View.VISIBLE);
holder.mImg_medication.setVisibility(View.VISIBLE);
int d = R.drawable.ic_type_pill;
try {
//Due to Offline requirements we do code like this get the images from our res folder
if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_pill")) {
d = R.drawable.ic_type_pill;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_patch")) {
d = R.drawable.ic_type_patch;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_capsule")) {
d = R.drawable.ic_type_capsule;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_ring")) {
d = R.drawable.ic_type_ring;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_inhaler")) {
d = R.drawable.ic_type_inhaler;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_spray")) {
d = R.drawable.ic_type_spray;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_bottle")) {
d = R.drawable.ic_type_bottle;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_drop")) {
d = R.drawable.ic_type_drop;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_pessaries")) {
d = R.drawable.ic_type_pessaries;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_sachets")) {
d = R.drawable.ic_type_sachets;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_tube")) {
d = R.drawable.ic_type_tube;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_suppository")) {
d = R.drawable.ic_type_suppository;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_injaction")) {
d = R.drawable.ic_type_injaction;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_spoon")) {
d = R.drawable.ic_type_spoon;
} else if (medication_typeBean.getType_image_name().equalsIgnoreCase("ic_type_powder")) {
d = R.drawable.ic_type_powder;
} else {
d = R.drawable.ic_type_pill;
}
Bitmap icon = BitmapFactory.decodeResource(mContext.getResources(),
d);
holder.mImg_medication.setImageBitmap(icon);
} catch (Exception e) {
Log.print(e);
}
// BitmapDrawable ob = new BitmapDrawable(mContext.getResources(), icon);
// img.setBackgroundDrawable(ob);
// holder.mImg_medication.setBackground(ob);
// Log.print("Type Adapter", "default " + position + ", selected " + selectedItem);
if (position == selectedItem) {
Log.print("Type adapter", "center" + position);
// holder.mTxt_Type.setTextColor(Color.parseColor("#76FF03"));
//holder.mImg_medication.setColorFilter(Color.GREEN);
// holder.mTxt_Type.setTextSize(35);
holder.mImg_medication.getLayoutParams().height = (int) mContext.getResources().getDimension(R.dimen.item_dob_width) + 10;
holder.mImg_medication.getLayoutParams().width = (int) mContext.getResources().getDimension(R.dimen.item_dob_width) + 10;
} else {
holder.mImg_medication.getLayoutParams().height = (int) mContext.getResources().getDimension(R.dimen.item_dob_width) - 10;
holder.mImg_medication.getLayoutParams().width = (int) mContext.getResources().getDimension(R.dimen.item_dob_width) - 10;
// holder.mTxt_Type.setTextColor(Color.WHITE);
//holder.mImg_medication.setColorFilter(null);
// holder.mTxt_Type.setVisibility(View.INVISIBLE);
// holder.mTxt_Type.setTextSize(18);
// holder.mImg_medication.getLayoutParams().height = 70;
// holder.mImg_medication.getLayoutParams().width = 70;
}
} else {
holder.mImg_medication.getLayoutParams().height = (int) mContext.getResources().getDimension(R.dimen.item_dob_width) - 10;
holder.mImg_medication.getLayoutParams().width = (int) mContext.getResources().getDimension(R.dimen.item_dob_width) - 10;
// holder.mTxt_Type.setVisibility(View.INVISIBLE);
holder.mImg_medication.setVisibility(View.INVISIBLE);
}
}
public void setSelecteditem(int selecteditem) {
this.selectedItem = selecteditem;
notifyDataSetChanged();
if (medication_lookBeanArrayList != null && Look_Adapter != null) {
NotifyLookChangetoType(selecteditem);
}
}
public int getSelecteditem() {
return selectedItem;
}
#Override
public int getItemCount() {
return medication_typeBeanArrayList.size();
}
#Override
public int getItemViewType(int position) {
Medication_TypeBean medication_typeBean = medication_typeBeanArrayList.get(position);
if (medication_typeBean.getType() == VIEW_TYPE_PADDING) {
return VIEW_TYPE_PADDING;
} else {
return VIEW_TYPE_ITEM;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
//public TextView mTxt_Type;
public ImageView mImg_medication;
public ViewHolder(View itemView) {
super(itemView);
// mTxt_Type = (TextView) itemView.findViewById(R.id.mTxt);
mImg_medication = (ImageView) itemView.findViewById(R.id.mImg_medication);
}
}
}
//Type Adapter ends ************************************************
I am not sure I get you properly but you want to change the data of one recyclerview and reset the value of other recyclerview
Try using recyclerView.scrollToPosition(INDEX_YOU_WANT_TO_SCROLL_TO);
IF YOU WANT TO ACHIEVE THE CENTER POSTION OF THE DATA USE
recyclerview.scrollToPosition(arraylist.size()/2);
arrayList in which your drawable data is stored
I tried to create Grid Layout for this I used below code. But in that code I don't know what is ItemView and how to implement it. When I put this code in my project I get error can not resolve symbol "ItemView". I got this code from below link -
https://stackoverflow.com/a/36143314/5726392
public class PrivateSeatViews extends FrameLayout implements View.OnClickListener {
private GridLayout mGridView;
private int mRowsCount;
private int mColsCount;
private int mCellSpace;
private OnItemClickListener mOnItemClickListener;
public PrivateSeatViews(Context context) {
super(context);
init(context, null);
}
// other constructors
private void init(Context context, AttributeSet attrs) {
// default values
View layout = inflate(getContext(), R.layout.grid_layout, null);
mGridView = (GridLayout) layout.findViewById(R.id.Lower);
mGridView.setRowCount(mRowsCount);
mGridView.setColumnCount(mColsCount);
mGridView.post(new Runnable() {
#Override
public void run() {
int width = getMeasuredWidth() / getColumnsCount();
int height = getMeasuredHeight() / getRowsCount();
for (int i = 0; i < getRowsCount(); i++) {
for (int j = 0; j < getColumnsCount(); j++) {
GridLayout.LayoutParams params = (GridLayout.LayoutParams) getChildAt(i, j).getL;
params.width = width;
params.height = height;
getChildAt(i, j).setLayoutParams(params);
}
}
}
});
addView(layout);
}
// this method allows to dinamically create grid
public void buildChildren(int rowsCount, int colsCount) {
mRowsCount = rowsCount;
mColsCount = colsCount;
mGridView.setRowCount(mRowsCount);
mGridView.setColumnCount(mColsCount);
buildChildren();
}
public void buildChildren() {
for (int i = 0; i < getRowsCount(); i++) {
for (int j = 0; j < getColumnsCount(); j++) {
ItemView1 view = new ItemView1(getContext(), i, j);
view.setOnClickListener(this);
mGridView.addView(view);
}
}
}
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
public ItemView getChildAt(int rowIndex, int columnIndex) {
int index = (getColumnsCount() * rowIndex) + columnIndex;
return (ItemView) mGridView.getChildAt(index);
}
public boolean isTouchOn(int rowIndex, int columnIndex) {
return getChildAt(rowIndex, columnIndex).isTouchOn();
}
public int getColumnsCount() {
return mGridView.getColumnCount();
}
public int getRowsCount() {
return mGridView.getRowCount();
}
#Override
public void onClick(View v) {
if (v instanceof ItemView) {
ItemView view = (ItemView) v;
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view);
}
}
}
public interface OnItemClickListener {
void onItemClick(ItemView view);
}
}
The best way i found to create the GridView is to use RecyclerView with the GridLayouy manager. Adapter implementations is the same as for normal RecyclerView
You can create GridLayout manager like this
//3 is the row span
GridLayoutManager a = new GridLayoutManager(this, 3);
This will help you to improve performance and create your view with the ViewHolder pattern
If you never used RecyclerView you can see a fine example here
I have an adapter which loads items from the List<> tempList.
At first, the tempList has 10 items. When users scroll to the bottom, 10 more items are added to tempList automatically, by getting items from another List propertyDetailsList.
for (int i = 0; i < 10; i++) {
tempList.add(propertyDetailsList.get(i));
}
propertyDetailsInstantAdapter.notifyDataSetChanged();
However, the result is that only the item at 0 (propertyDetailsList.get(0)) is added to tempList, and it is added 10 times instead....
Whats wrong with my code?
More code:
private ListView propertyList;
private List<PropertyDetails> tempList;
private List<PropertyDetails> propertyDetailsList;
......
propertyDetailsList = getList();
tempList = propertyDetailsList.subList(0, 10);
......
public void showPropertyList() {
propertyList.setAdapter(buildPropertyList());
mIsLoading = false;
propertyList.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!mIsLoading && mMoreDataAvailable) {
if (totalItemCount - visibleItemCount - AUTOLOAD_THRESHOLD <= firstVisibleItem) {
mIsLoading = true;
for (int i = 0; i < 10; i++) {
tempList.add(propertyDetailsList.get(10 + i));
}
propertyDetailsInstantAdapter.notifyDataSetChanged();
mIsLoading = false;
}
}
}
});
}
public InstantAdapter<PropertyDetails> buildPropertyList() {
propertyDetailsInstantAdapter = new InstantAdapter<PropertyDetails>(
this, R.layout.property_list_item, PropertyDetails.class, tempList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PropertyListItem propertyListItem;
Context context = parent.getContext();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.property_list_item, parent, false);
propertyListItem = new PropertyListItem();
propertyListItem.propertyImage = (ImageView) convertView.findViewById(R.id.propertyListImage);
propertyListItem.propertyAddress = (TextView) convertView.findViewById(R.id.propertyListAddress);
propertyListItem.propertyName = (TextView) convertView.findViewById(R.id.propertyListName);
propertyListItem.propertyDetails = this.getItem(position);
convertView.setTag(propertyListItem);
} else {
propertyListItem = (PropertyListItem) convertView.getTag();
}
final PropertyDetails propertyDetails = this.getItem(position);
Transformation transformation = new Transformation() {
#Override
public Bitmap transform(Bitmap source) {
int targetWidth = sp.getInt("deviceWidth", 0);
double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
int targetHeight = (int) (targetWidth * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
// Same bitmap is returned if sizes are the same
source.recycle();
}
return result;
}
#Override
public String key() {
return "transformation" + " desiredWidth";
}
};
if (propertyDetails.getImg_link() != null) {
Picasso.with(context)
.load(Uri.parse(propertyDetails.getImg_link()))
.transform(transformation)
.into(propertyListItem.propertyImage);
}
propertyListItem.propertyAddress.setText(propertyDetails.getPropertyAddress());
propertyListItem.propertyName.setText(propertyDetails.getPropertyName());
return convertView;
}
};
return propertyDetailsInstantAdapter;
}
Hiii
i have to create circular menu after R & D i got the following output which is display in image 1 but i want to give effect like image 2 i will put it my code here so you can check it
My current Output image 1 in this button and text display horizontally i want to convert this to arc effect both button and text like below image 2
i want to make this buttons like this image
MainActivity.java
public class MainActivity extends MenuActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override public void createButtons() {
for(int i = 0 ; i < 3 ; i++) {
RotativeButton button = new RotativeButton(this);
if(i==0)
{
button.setBackgroundResource(R.drawable.green);
//button.setBackgroundColor(Color.GREEN);
button.setText("Insurance Green");
button.setPosition(i);
button.setLabel("OPTION "+(i+1));
button.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
}
if(i==1)
{
button.setBackgroundResource(R.drawable.red);
//button.setBackgroundColor(Color.RED);
button.setText("Insurance Red");
button.setPosition(i);
button.setLabel("OPTION "+(i+1));
button.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
}
if(i==2)
{
button.setBackgroundResource(R.drawable.yellow);
//button.setBackgroundColor(Color.YELLOW);
button.setText("Insurance Yellow");
button.setPosition(i);
button.setLabel("OPTION "+(i+1));
button.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
}
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("id", String.valueOf(i+1));
button.setIntent(intent);
mButtonList.add(button);
}
}
}
MenuActivity.java
public abstract class MenuActivity extends Activity {
protected List<RotativeButton> mButtonList = new ArrayList<RotativeButton>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.common_view);
// RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainView);
LinearLayout mainLayout=(LinearLayout)findViewById(R.id.mainView);
getLayoutInflater().inflate(R.layout.menu, mainLayout, true);
final RotativeMenuView customView = (RotativeMenuView) findViewById(R.id.rotativeMenuView);
final Button okBtn = (Button) customView.findViewById(R.id.okBtn);
customView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
public void onGlobalLayout()
{
if(okBtn.getVisibility()==View.VISIBLE)
{
customView.addButtons(mButtonList);
customView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
createButtons();
}
protected abstract void createButtons();
}
RotativeButton.java
public class RotativeButton extends Button {
private int position;
private Intent intent;
private String label;
public RotativeButton(Context context) {
super(context);
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Intent getIntent() {
return intent;
}
public void setIntent(Intent intent) {
this.intent = intent;
}
}
RotativeMenuView.java
public class RotativeMenuView extends RelativeLayout
{
private List<RotativeButton> _buttonList;
private HashMap<Integer, Point > _pointForPosition = new HashMap<Integer, Point>();
private HashMap<Integer, RectF > _rectForPosition = new HashMap<Integer, RectF>();
private TextView titleTv;
public RotativeMenuView(Context context) {
super(context);
}
public RotativeMenuView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public RotativeMenuView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public void addButtons(List<RotativeButton> buttonList) {
final Button okBtn = (Button) findViewById(R.id.okBtn);
titleTv = (TextView) findViewById(R.id.labelTv);
okBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
RotativeButton activeButton = getActiveButton();
Intent i = activeButton.getIntent();
getContext().startActivity(i);
}
});
_buttonList = buttonList;
int numberOfButtons = buttonList.size();
final double angle = 360 / numberOfButtons;
int okWidth = okBtn.getMeasuredWidth();
int okHeight = okBtn.getMeasuredHeight();
Log.e("OK_WIDTH", String.valueOf(okWidth));
Log.e("OK_HEIGHT", String.valueOf(okHeight));
int okLeft = okBtn.getLeft();
int okTop = okBtn.getTop();
Log.e("okLeft", String.valueOf(okLeft));
Log.e("okTop", String.valueOf(okTop));
int distance = okWidth;
Log.e("distance", String.valueOf(distance));
final int[] point = new int[2];
okBtn.getLocationInWindow(point);
for (int i = 0; i < numberOfButtons; i++) {
RotativeButton rotativeButton = buttonList.get(i);
int position = rotativeButton.getPosition();
int buttonHeight = rotativeButton.getBackground()
.getIntrinsicHeight();
int buttonWidth = rotativeButton.getBackground()
.getIntrinsicWidth();
int diffHeight = (okHeight / 2) - (buttonHeight / 2);
int diffWidth = (okWidth / 2) - (buttonWidth / 2);
float newAngle = (float) angle * position;
Point nextPoint = nextPosition(okTop + diffHeight, okLeft
+ diffWidth, newAngle, distance);
int newLeft = nextPoint.x;
int newTop = nextPoint.y;
final RectF okRect = new RectF(point[0] - newLeft
- okBtn.getWidth() + diffWidth, point[1] - newTop
- okBtn.getHeight() + diffHeight, (point[0] - newLeft)
+ okBtn.getWidth() + diffWidth, (point[1] - newTop)
+ okBtn.getHeight() + diffHeight);
rotativeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final RotativeButton clickedButton = (RotativeButton) v;
int position = clickedButton.getPosition();
if (position == 0) {
return;
}
int total = _buttonList.size();
final int clickedPosition = total - position;
double angle = 360 / total;
titleTv.setVisibility(INVISIBLE);
for (int i = 0; i < total; i++) {
final RotativeButton currentButton = _buttonList.get(i);
position = currentButton.getPosition();
RectF rectF = _rectForPosition.get(position);
float startAngle = (float) angle * position;
Path aPath = new Path();
aPath.addArc(rectF, startAngle, (float) angle
* clickedPosition);
Animation anim = new PathAnimation(aPath);
anim.setDuration(500);
anim.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {
currentButton.setClickable(false);
okBtn.setClickable(false);
}
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationEnd(Animation animation) {
currentButton.setClickable(true);
okBtn.setClickable(true);
updatePosition(currentButton, clickedPosition);
currentButton.clearAnimation();
}
});
anim.setFillBefore(true);
currentButton.startAnimation(anim);
}
}
});
LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.topMargin = newTop;
params.leftMargin = newLeft;
addView(rotativeButton, params);
if (position == 0) {
applyLabel(rotativeButton.getLabel());
}
_pointForPosition.put(position, nextPoint);
_rectForPosition.put(position, okRect);
}
}
public void updatePosition(final RotativeButton currentButton, int diffPosition){
int total = _buttonList.size();
int currentPosition = currentButton.getPosition();
int newPosition = currentPosition + diffPosition;
if(newPosition >= total ){
newPosition -= total;
}
currentButton.setPosition(newPosition);
Point pointForPosition = _pointForPosition.get(newPosition);
int newLeft = pointForPosition.x;
int newTop = pointForPosition.y;
Log.d("CustomView", "Button: "+ currentButton.getPosition()+ "("+currentButton.getLabel()+") , New Left:" +newLeft+" top: "+ newTop);
currentButton.layout(newLeft, newTop,
newLeft + currentButton.getMeasuredWidth(), newTop + currentButton.getMeasuredHeight());
Log.d("CustomView", "Moving from:" +currentPosition+" to: "+currentButton.getPosition() + "code: " +currentButton.getLabel());
if (newPosition == 0) {
applyLabel(currentButton.getLabel());
}
}
protected void applyLabel( String label) {
titleTv.setText(label.toUpperCase());
titleTv.setVisibility(VISIBLE);
}
private Point nextPosition(int okTop, int okLeft, double angle, int distance) {
int x = okLeft + (int) (distance*Math.cos(Math.toRadians(angle)));
int y = okTop + (int) (distance*Math.sin(Math.toRadians(angle)));
Log.e("X", String.valueOf(x));
Log.e("Y", String.valueOf(y));
Point p = new Point();
p.set(x, y);
return p;
}
private RotativeButton getActiveButton()
{
for (RotativeButton aButton : _buttonList)
{
int position = aButton.getPosition();
if(position == 0)
{
return aButton;
}
}
return null;
}
}
PathAnimation.java
public class PathAnimation extends Animation {
private PathMeasure measure;
private float[] pos = new float[2];
public PathAnimation(Path path) {
measure = new PathMeasure(path, false);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t){
measure.getPosTan(measure.getLength() * interpolatedTime, pos,null);
t.getMatrix().setTranslate(pos[0], pos[1]);
}
}
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