seekbar using volume increment and decrement for 0.12 and 0.13 combination like 0.12,0.25,0.37,0.50,0.62,0.75,0.87 but i getting values like this 0.12,0.25,0.38,0.50,0.62,0.75,0.88 .Please suggest me how can i clear the issues.
public class MainActivity extends Activity {
Button b1;
SeekBar sk1;
double point=0.12;
double value=0.00;
int previous=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
sk1=(SeekBar) findViewById(R.id.seekBar1);
sk1.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
// TODO Auto-generated method stub
int p = progress;
double f = progress;
double x = Double.parseDouble(b1.getText().toString());
if (point == 0.12)
{
if (previous > p)
{
if (x == -20.00 )
{
}
else {
float a = (float) (0.25 / 2 * 100) / 100;
f = value - a;
b1.setText(""+ String.format("%.2f",(f)));
value=f;
}
}
else if (previous < p)
{
if (x == 20.00)
{
}
else {
float a = (float) (0.25 / 2 * 100) / 100;
f = value + a;
b1.setText(""+ String.format("%.2f",(f)));
value=f;
}
}
}
previous = progress;
}
});
}
Related
I'm trying to do a division (double/double) and the result is Infinity. Can someone help me and explain why that's happening?
I searched some forums, but I didn't get the answer.
I have something like that:
public class CalculoSapIsolada extends AppCompatActivity
{
double areaAcoX;
double numeroBarrasX;
double areaBarraX;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculo_sap_isolada);
//Here is where i get the value of areaBarraX
if(SapataIsolada.getAço()==50)
{
final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner_diametro_aço_x);
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.diametro_aço_CA_50, android.R.layout.simple_spinner_item);
staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
staticSpinner.setAdapter(staticAdapter);
staticSpinner.setPrompt("Selecione o diâmetro da armadura");
staticSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
Object item = adapterView.getItemAtPosition(i);
if (i == 0) {
diametroAçoX = 0.5;
areaBarraX = 0.196;
}
if (i == 1) {
diametroAçoX = 0.63;
areaBarraX = 0.31;
}
if (i == 2) {
diametroAçoX = 0.8;
areaBarraX = 0.5;
}
if (i == 3) {
diametroAçoX = 1;
areaBarraX = 0.785;
}
if (i == 4) {
diametroAçoX = 1.25;
areaBarraX = 1.22;
}
if (i == 5) {
diametroAçoX = 1.6;
areaBarraX = 2.01;
}
if (i == 6) {
diametroAçoX = 2;
areaBarraX = 3.14;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
/* the value of areaAcoX is calculated previously and during the testrun it receives areaAcoX=11.36016 and the value of areaBarraX=0.5 */
numeroBarrasX=areaAcoX/areaBarraX;
Button calcular =(Button)findViewById(R.id.calcular_resultado);
calcular.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//in altura.setText, areaAcoX==11.36016
TextView altura = (TextView)findViewById(R.id.alturaTotal);
altura.setText(""+areaAcoX);
//In ladoLtopo.setText, areaBarraX==0.5
TextView ladoLtopo = (TextView)findViewById(R.id.ladoL_topo);
ladoLtopo.setText(""+areaBarraX);
//In numBarrasX.setText, numeroBarrasX==Infinity
TextView numBarrasX = (TextView)findViewById(R.id.numeroBarras_x);
numBarrasX.setText(""+numeroBarrasX);
});
}
}
I have some similar operations in the code that is not shown here and I didn't get the infinity error in their value.
Dividing by 0.0 of type double yields infinity. Perhaps there's a divide by 0.0 at this line before areaBarraX has been initialized:
numeroBarrasX=areaAcoX/areaBarraX;
Recently I'm making a game which requires continuous animation.
I'll explain it further.
I got view let's say top of the screen and I need to animate it from the top of the screen to the bottom of the screen and then it will go back to the original spot (Top of the screen) when the view is on the bottom.
Now there's 6 views which does the exactly same thing.
Animate from top of the screen to the bottom of the screen and back when they are on the bottom.
But when they are already moving there's really annoying stuttering and lags on the application.
Here's the code :
#Override
public void onWindowFocusChanged(boolean focus) {
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!failedM) {
running = true;
soundPool.play(click_sound, 1, 1, 0, 0, 1);
play.setVisibility(View.INVISIBLE);
p1.setVisibility(View.VISIBLE);
p2.setVisibility(View.VISIBLE);
p3.setVisibility(View.VISIBLE);
c1.setVisibility(View.VISIBLE);
c2.setVisibility(View.VISIBLE);
c3.setVisibility(View.VISIBLE);
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.post(new Runnable() {
#Override
public void run() {
p1.getHitRect(rect1);
p2.getHitRect(rect2);
p3.getHitRect(rect3);
c1.getHitRect(rect4);
c2.getHitRect(rect5);
c3.getHitRect(rect6);
if (Rect.intersects(rect, rect1)
{
.....
}
if (Rect.intersects(rect, rect2)
) {
.....
}
if (Rect.intersects(rect, rect3)
) {
.....
}
if (Rect.intersects(rect, rect4)
) {
.....
}
if (Rect.intersects(rect, rect5)
) {
.....
}
if (Rect.intersects(rect, rect6)
) {
.....
}
downy1 += 1;
downy2 += 1;
downy3 += 1;
downy4 += 1;
downy5 += 1;
downy6 += 1;
params1.topMargin = params1.topMargin
+ downy1;
params2.topMargin = params2.topMargin
+ downy2;
params3.topMargin = params3.topMargin
+ downy3;
params4.topMargin = params4.topMargin
+ downy4;
params5.topMargin = params5.topMargin
+ downy5;
params6.topMargin = params6.topMargin
+ downy6;
p1.setLayoutParams(params1);
p2.setLayoutParams(params2);
p3.setLayoutParams(params3);
c1.setLayoutParams(params4);
c2.setLayoutParams(params5);
c3.setLayoutParams(params6);
if (p1.getTop() > height) {
downy1 = 0;
params1.leftMargin = newX;
params1.topMargin = orig1y;
p1.setLayoutParams(params1);
}
if (p2.getTop() > height) {
downy2 = 0;
params2.leftMargin = newX;
params2.topMargin = orig2y;
p2.setLayoutParams(params2);
}
if (p3.getTop() > height) {
downy3 = 0;
params3.leftMargin = newX;
params3.topMargin = orig3y;
p3.setLayoutParams(params3);
}
if (c1.getTop() > height
&& !failedM) {
downy4 = 0;
params4.leftMargin = newX;
params4.topMargin = orig4y;
c1.setLayoutParams(params4);
}
if (c2.getTop() > height
&& !failedM) {
downy5 = 0;
params5.leftMargin = newX;
params5.topMargin = orig5y;
c2.setLayoutParams(params5);
}
if (c3.getTop() > height
&& !failedM) {
downy6 = 0;
params6.leftMargin = newX;
params6.topMargin = orig6y;
c3.setLayoutParams(params6);
}
}
});
}
}
}).start();
}
});
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
As you can see there's (if view.getTop() > height)
What it means is that when the view Y is bigger than the height which is when the view is moving from the top to the bottom it will go back to the top.
I hope I made it clear
Thanks in advance.
You should use the animation framework. (view.animate()...).
Setting layout params requires re-calculating the layout, which is potentially not a cheap operation (depends on your layout).
You can use animation framework or set translateX/Y etc properties of the view, which avoid re-calculating the layout.
So Im doing a little up, not a big deal, just learning graphics, but when i click on the back button, the app crashes and it gives me fatal error 11.
Code:
public class MyPachuSurface extends SurfaceView implements Runnable{
SurfaceHolder myHolder;
Thread myThread = null;
boolean isRunning = false;
public float x,y,startX,startY,finalX,finalY,dx,dy,tx,ty;
public MyPachuSurface(Context context)
{
super(context);
// TODO Auto-generated constructor stub
myHolder = getHolder();
this.x = 0;
this.y = 0;
this.startX = 0;
this.startY = 0;
this.finalX = 0;
this.finalY = 0;
this.dx = 0;
this.dy = 0;
this.tx = 0;
this.ty = 0;
}
public void pause()
{
isRunning = false;
try
{
myThread.join();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myThread = null;
}
public void resume ()
{
isRunning = true;
myThread = new Thread(this);
myThread.start();
}
#Override
public void run()
{
// TODO Auto-generated method stub
while(isRunning)
{
if(!myHolder.getSurface().isValid())
continue;
Canvas canvas = myHolder.lockCanvas();
canvas.drawRGB(02, 02, 254);
if(this.x != 0 && this.y != 0)
{
Bitmap test = BitmapFactory.decodeResource(getResources(), R.drawable.plus1);
canvas.drawBitmap(test, this.x - test.getWidth()/2 - this.tx, this.y - test.getHeight()/2 - this.ty, null);
this.tx += this.dx/30;
this.ty += this.dy/30;
}
myHolder.unlockCanvasAndPost(canvas);
}
}
}
This is the view, and this is the activity :
public class MyGraphicsSurface extends Activity implements OnTouchListener{
MyPachuSurface pachuSurf;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
pachuSurf = new MyPachuSurface(this);
pachuSurf.setOnTouchListener(this);
setContentView(pachuSurf);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
pachuSurf.resume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
pachuSurf.resume();
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
// TODO Auto-generated method stub
this.pachuSurf.x = event.getX();
this.pachuSurf.y = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
pachuSurf.startX = event.getX();
pachuSurf.startY = event.getY();
pachuSurf.tx = 0;
pachuSurf.ty = 0;
break;
case MotionEvent.ACTION_UP:
pachuSurf.finalX = event.getX();
pachuSurf.finalY = event.getY();
pachuSurf.dx = pachuSurf.finalX - pachuSurf.startX;
pachuSurf.dy = pachuSurf.finalY - pachuSurf.startY;
break;
}
return true;
}
}
And This is The Loc Cat:
06-06 17:37:20.104: E/AndroidRuntime(22781): FATAL EXCEPTION: Thread-29865
06-06 17:37:20.104: E/AndroidRuntime(22781): java.lang.NullPointerException
06-06 17:37:20.104: E/AndroidRuntime(22781): at com.example.myfirstapp.MyPachuSurface.run(MyPachuSurface.java:68)
06-06 17:37:20.104: E/AndroidRuntime(22781): at java.lang.Thread.run(Thread.java:856)
I have a custom listview which is having a custom inexscroller which draws itself when you scroll through the list. Now that doesnt look nice when my listview is not having too many items. So what I want to do is to hide the IndexScroller when the items are less than a particular number to be scrollable. I have done everything but I am not able to hide the list view. Please help:
Here are the classes used:
IndexableListViewActivity
public class IndexableListViewActivity extends Activity implements OnClickListener
{
private ArrayList<String> mItems;
private IndexableListView mListView;
TextView MyTasks, TeamTasks, username, fullusername;
RelativeLayout listlay;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mItems = new ArrayList<String>();
mItems.add("Diary of a Wimpy Kid 6: Cabin Fever");
mItems.add("Steve Jobs");
mItems.add("Inheritance (The Inheritance Cycle)");
mItems.add("11/22/63: A Novel");
mItems.add("The Hunger Games");
mItems.add("The LEGO Ideas Book");
mItems.add("Explosive Eighteen: A Stephanie Plum Novel");
mItems.add("Catching Fire (The Second Book of the Hunger Games)");
mItems.add("Elder Scrolls V: Skyrim: Prima Official Game Guide");
mItems.add("Death Comes to Pemberley");
mItems.add("Diary of a Wimpy Kid 6: Cabin Fever");
mItems.add("Steve Jobs");
mItems.add("Inheritance (The Inheritance Cycle)");
mItems.add("11/22/63: A Novel");
mItems.add("The Hunger Games");
mItems.add("The LEGO Ideas Book");
mItems.add("Explosive Eighteen: A Stephanie Plum Novel");
mItems.add("Catching Fire (The Second Book of the Hunger Games)");
mItems.add("Elder Scrolls V: Skyrim: Prima Official Game Guide");
mItems.add("Death Comes to Pemberley");
mItems.add("Make this list longer");
mItems.add("A");
mItems.add("B");
// mItems.add("C");
// mItems.add("D");
// mItems.add("E");
// mItems.add("F");
// mItems.add("H");
// mItems.add("I");
// mItems.add("J");
// mItems.add("K");
// mItems.add("L");
// mItems.add("M");
// mItems.add("N");
// mItems.add("O");
// mItems.add("P");
// mItems.add("Q");
// mItems.add("R");
// mItems.add("S");
// mItems.add("T");
// mItems.add("U");
// mItems.add("V");
// mItems.add("W");
// mItems.add("X");
// mItems.add("Y");
// mItems.add("Z");
Collections.sort(mItems);
ContentAdapter adapter = new ContentAdapter(this,
android.R.layout.simple_list_item_1, mItems);
mListView = (IndexableListView) findViewById(R.id.listview);
mListView.setAdapter(adapter);
mListView.setFastScrollEnabled(true);
MyTasks = (TextView)findViewById(R.id.myTasks);
MyTasks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MyTasks.setBackgroundResource(R.drawable.rectangle_selected);
TeamTasks.setBackgroundResource(R.drawable.rectangle);
if(mListView.getLastVisiblePosition() + 1 == mListView.getCount()) {
Toast.makeText(getBaseContext(), "No need to scroll", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Need to scroll", Toast.LENGTH_SHORT).show();
}
}
});
TeamTasks = (TextView)findViewById(R.id.teamTasks);
TeamTasks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TeamTasks.setBackgroundResource(R.drawable.rectangle_selected);
MyTasks.setBackgroundResource(R.drawable.rectangle);
}
});
}
private class ContentAdapter extends ArrayAdapter<String> implements SectionIndexer {
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public ContentAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
}
#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;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
StrngMatcher.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 {
int vi = value.charAt(i);
int kj = keyword.charAt(j);
if (isKorean(vi) && isInitialSound(kj)) {
} else {
if (vi == kj) {
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(int i) {
return false;
}
private static boolean isInitialSound(int i) {
return false;
}
}
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
if(mScroller!=null)
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);
}
}
IndexScroller.java
public class IndexScroller {
private float mIndexbarWidth;
private float mIndexbarMargin;
private float mPreviewPadding;
private float mDensity;
private float mScaledDensity;
private float mAlphaRate;
private int mState = STATE_HIDDEN;
private int mListViewWidth;
private int mListViewHeight;
private int mCurrentSection = -1;
private boolean mIsIndexing = false;
private ListView mListView = null;
private SectionIndexer mIndexer = null;
private String[] mSections = null;
private RectF mIndexbarRect;
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 = 2 * 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;
}
}
};
}
In this, IndexableListView and IndexScroller are in same package and other 2 classes are in 2 different packages.
Please help how to just hide the IndexScroller so that it doesnt show up on touches.
Since no one bothered to answer, here is the thing to be done.,
For all lines where state is set as shown in IndexScroller.java, enclose them in:
isTrue = mListView.getLastVisiblePosition() + 1 == mListView.getCount();
if(!isTrue)
{
//State Shown
}
I had written a code to move a ball with the help of accelerometer in android such that if it touches any of 4 edges it reappears on opposide edge my problems are
1.ball is not reappearing on opposite edge
2.orientation changes to lanscape
here is my code
public class Accelerate extends Activity implements SensorEventListener {
float x, y, sensorX, sensorY, a, b, centerX, centerY;
Bitmap ball;
SensorManager sm;
NixSurface ourSurfaceView;
public class NixSurface extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public NixSurface(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(255, 255, 255);
centerX = canvas.getWidth() / 2;
centerY = canvas.getHeight() / 2;
x += sensorX;
y += sensorY;
a = centerX + x;
b = centerY + y;
if (a > canvas.getWidth())
a = 0;
if (b > canvas.getHeight())
b = 0;
if (a < 0)
a = canvas.getWidth();
if (b < 0)
b = canvas.getHeight();
canvas.drawBitmap(ball, a, b, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) {
Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
x = y = sensorY = sensorX = 0;
ball = BitmapFactory.decodeResource(getResources(), R.drawable.nix);
ourSurfaceView = new NixSurface(this);
ourSurfaceView.resume();
setContentView(ourSurfaceView);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
sm.unregisterListener(this);
super.onStop();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
// nothing to do here
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
try {
Thread.sleep(16);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sensorX = -event.values[0];
sensorY = event.values[1];
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
I guess your problem is that you assume that the sensor origin (x=0,y=0) is the screen center. The sensor origin is the top left corner of the screen (X pointing left and Y pointing down), so comparing a & b to canvas.getWidth() & canvas.getHeight() is not correct since you already added centerX & centerY. Also, negating sensorX will cause the condition a > canvas.getWidth() to never occur since X is never negative.