Android String Array - android

Hello all i have the code below which produces four wheels each with the numbers 0-9. I think these numbers are being called for each wheel in the section of code after:
/**
* Initializes wheel
* #param id the wheel widget Id
*/
Is there a way i can change this so i can set certain WORDS instead of NUMBERS for each one of the four wheels like and array or string.
So i would have four arrays (strings) with different words for each wheel.
Thanks in advance.
public class PasswActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passw_layout);
initWheel(R.id.passw_1);
initWheel(R.id.passw_2);
initWheel(R.id.passw_3);
initWheel(R.id.passw_4);
Button mix = (Button)findViewById(R.id.btn_mix);
mix.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mixWheel(R.id.passw_1);
mixWheel(R.id.passw_2);
mixWheel(R.id.passw_3);
mixWheel(R.id.passw_4);
}
});
}
// Wheel scrolled flag
private boolean wheelScrolled = false;
// Wheel scrolled listener
OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
}
};
// Wheel changed listener
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
/**
* Initializes wheel
* #param id the wheel widget Id
*/
private void initWheel(int id) {
WheelView wheel = getWheel(id);
wheel.setViewAdapter(new NumericWheelAdapter(this, 0, 9));
wheel.setCurrentItem((int)(Math.random() * 10));
wheel.addChangingListener(changedListener);
wheel.addScrollingListener(scrolledListener);
wheel.setCyclic(true);
wheel.setInterpolator(new AnticipateOvershootInterpolator());
}
/**
* Returns wheel by Id
* #param id the wheel Id
* #return the wheel with passed Id
*/
private WheelView getWheel(int id) {
return (WheelView) findViewById(id);
}
/**
* Tests entered PIN
* #param v1
* #param v2
* #param v3
* #param v4
* #return true
*/
private boolean testPin(int v1, int v2, int v3, int v4) {
return testWheelValue(R.id.passw_1, v1) && testWheelValue(R.id.passw_2, v2) &&
testWheelValue(R.id.passw_3, v3) && testWheelValue(R.id.passw_4, v4);
}
/**
* Tests wheel value
* #param id the wheel Id
* #param value the value to test
* #return true if wheel value is equal to passed value
*/
private boolean testWheelValue(int id, int value) {
return getWheel(id).getCurrentItem() == value;
}
/**
* Mixes wheel
* #param id the wheel id
*/
private void mixWheel(int id) {
WheelView wheel = getWheel(id);
wheel.scroll(-25 + (int)(Math.random() * 50), 2000);
}
}

Just use an ArrayWheelAdapter<T> instead of the NumericWheelAdapter.
If you look closely at your own code, you will find a line where your adapter is created
new NumericWheelAdapter(this, 0, 9)
An adaptor is something the wheel UI can hook onto and grab data to display. This will create an adapter containing the numbers zero through nine. To create an adapter that displays the words "Abc", "Foo", and "Bar" use this.
new ArrayWheelAdapter<String>(this, new String[]{"Abc", "Foo", "Bar"})

Related

Android-Charts -- CandleStick Chart

Hi i am using https://github.com/limccn/Android-Charts library for showing stock live data on chart in my android app. i am using CandleStick Chart of this library. everything is working fine except one thing is that i am not able to show tool tip when mouse over on any candle stick inside chart for display data. i am using below code for initializing chart. does any one know how to show tool tip or how we can attached any view when user mouse over on any stick of chart.
private void initChart() {
for (int i = 0; i < chartData.size(); i++) {
//OHLCEntity(double open, double high, double low, double close, int date)
ChartData chartdata = chartData.get(i);
String dateString = chartdata.getT_Time().substring(0, chartdata.getT_Time().lastIndexOf("T"));
String timeString = chartdata.getT_Time().substring(chartdata.getT_Time().lastIndexOf("T") + 1, chartdata.getT_Time().toString().length());
Pattern p = Pattern.compile(":");
String[] times = p.split(timeString);
String dateValue = "";
if (times.length >= 3) {
dateValue = dateString.replaceAll("-", "").trim().toString() + times[0].trim().toString() + "" + times[1].toString().trim();
} else {
dateValue = dateString.replaceAll("-", "").trim().toString();
}
ohlc.add(new OHLCEntity(chartdata.getT_Open(), chartdata.getHigh(), chartdata.getLow(), chartdata.getT_Close(), Integer.valueOf(dateValue)));
}
ChartData maxds = Collections.max(chartData, new ChartComparator());
candlestickchart.setAxisXColor(Color.LTGRAY);
candlestickchart.setAxisYColor(Color.LTGRAY);
candlestickchart.setLatitudeColor(Color.GRAY);
candlestickchart.setLongitudeColor(Color.GRAY);
candlestickchart.setBorderColor(Color.LTGRAY);
candlestickchart.setLongitudeFontColor(Color.WHITE);
candlestickchart.setLatitudeFontColor(Color.WHITE);
// 最大显示足数
candlestickchart.setMaxSticksNum(chartData.size());
// 最大纬线数
// candlestickchart.setLatitudeNum(5);
// // 最大经线数
// candlestickchart.setLongitudeNum(3);
// 最大价格
candlestickchart.setMaxValue(maxds.getVolume());
// 最小价格
int minIndex = chartData.indexOf(Collections.min(chartData, new ChartComparator()));
candlestickchart.setMinValue(chartData.get(minIndex).getVolume());
candlestickchart.setDisplayLongitudeTitle(true);
candlestickchart.setDisplayLatitudeTitle(true);
candlestickchart.setDisplayLatitude(true);
candlestickchart.setDisplayLongitude(true);
candlestickchart.setBackgroundColor(Color.BLACK);
candlestickchart.setDataQuadrantPaddingTop(5);
candlestickchart.setDataQuadrantPaddingBottom(5);
candlestickchart.setDataQuadrantPaddingLeft(5);
candlestickchart.setDataQuadrantPaddingRight(5);
// candlestickchart.setAxisYTitleQuadrantWidth(50);
// candlestickchart.setAxisXTitleQuadrantHeight(20);
candlestickchart.setAxisXPosition(Axis.AXIS_X_POSITION_BOTTOM);
candlestickchart.setAxisYPosition(Axis.AXIS_Y_POSITION_RIGHT);
// 为chart2增加均线
candlestickchart.setStickData(new ListChartData<IStickEntity>(ohlc));
candlestickchart.setOnDisplayCursorListener(new IDisplayCursorListener() {
public void onCursorChanged(IDataCursor dataCursor, int displayFrom,
int displayNumber) {
candlestickchart.setDisplayFrom(displayFrom);
candlestickchart.setDisplayNumber(displayNumber);
candlestickchart.postInvalidate();
}
});
candlestickchart.setOnTouchGestureListener(new OnTouchGestureListener() {
/* (non-Javadoc)
*
* #param touchable
* #param event
* #see cn.limc.androidcharts.event.OnTouchGestureListener#onTouchDown(cn.limc.androidcharts.event.ITouchable, android.view.MotionEvent)
*/
#Override
public void onTouchDown(ITouchable touchable, MotionEvent event) {
super.onTouchDown(touchable, event);
candlestickchart.touchDown(new PointF(event.getX(), event.getY()));
}
/* (non-Javadoc)
*
* #param touchable
* #param event
* #see cn.limc.androidcharts.event.OnTouchGestureListener#onTouchMoved(cn.limc.androidcharts.event.ITouchable, android.view.MotionEvent)
*/
#Override
public void onTouchMoved(ITouchable touchable, MotionEvent event) {
super.onTouchMoved(touchable, event);
candlestickchart.touchMoved(new PointF(event.getX(), event.getY()));
}
/* (non-Javadoc)
*
* #param touchable
* #param event
* #see cn.limc.androidcharts.event.OnTouchGestureListener#onTouchUp(cn.limc.androidcharts.event.ITouchable, android.view.MotionEvent)
*/
#Override
public void onTouchUp(ITouchable touchable, MotionEvent event) {
super.onTouchUp(touchable, event);
candlestickchart.touchUp(new PointF(event.getX(), event.getY()));
}
});
candlestickchart.setAutoCalcValueRange(true);
candlestickchart.setDisplayCrossXOnTouch(true);
candlestickchart.setDisplayCrossYOnTouch(true);
}
If you want to get the selected stick data index, you can use:
public int getSelectedIndex()
If you want to get the touched Point, you can use:
Inside setOnTouchGestureListener:
public void onTouchMoved(ITouchable touchable, MotionEvent event){
new PointF(event.getX(), event.getY())
}
Outside setOnTouchGestureListener (Activity, Fragment, ViewGroup):
public PointF getTouchPoint()
For more features supports, choose SlipCandleStickChart.

About the "onDoubleTap" function in android developer sample "InteractiveChart",

I want to learn how to handle the image and gesture function in android.
So I read the sample "InteractiveChart" under "Animating a Scroll Gesture" section in Android developer website.
While I read about "onDoubleTap" method in InteractiveLineGraphView.java.
#Override
public boolean onDoubleTap(MotionEvent e) {
mZoomer.forceFinished(true);
if (hitTest(e.getX(), e.getY(), mZoomFocalPoint)) {
mZoomer.startZoom(ZOOM_AMOUNT);
}
ViewCompat.postInvalidateOnAnimation(InteractiveLineGraphView.this);
return true;
}
I checked the code of Zoomer.
It mainly calls DecelerateInterpolator method and set some variables.
I wonder how can "Zoomer" achieve the double tap zoom function.
Does "DecelerateInterpolator" do the work? Or I just missed something?
public class Zoomer {
/**
* The interpolator, used for making zooms animate 'naturally.'
*/
private Interpolator mInterpolator;
/**
* The total animation duration for a zoom.
*/
private int mAnimationDurationMillis;
/**
* Whether or not the current zoom has finished.
*/
private boolean mFinished = true;
/**
* The current zoom value; computed by {#link #computeZoom()}.
*/
private float mCurrentZoom;
/**
* The time the zoom started, computed using {#link android.os.SystemClock#elapsedRealtime()}.
*/
private long mStartRTC;
/**
* The destination zoom factor.
*/
private float mEndZoom;
public Zoomer(Context context) {
mInterpolator = new DecelerateInterpolator();
mAnimationDurationMillis = context.getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
/**
* Forces the zoom finished state to the given value. Unlike {#link #abortAnimation()}, the
* current zoom value isn't set to the ending value.
*
* #see android.widget.Scroller#forceFinished(boolean)
*/
public void forceFinished(boolean finished) {
mFinished = finished;
}
/**
* Aborts the animation, setting the current zoom value to the ending value.
*
* #see android.widget.Scroller#abortAnimation()
*/
public void abortAnimation() {
mFinished = true;
mCurrentZoom = mEndZoom;
}
/**
* Starts a zoom from 1.0 to (1.0 + endZoom). That is, to zoom from 100% to 125%, endZoom should
* by 0.25f.
*
* #see android.widget.Scroller#startScroll(int, int, int, int)
*/
public void startZoom(float endZoom) {
mStartRTC = SystemClock.elapsedRealtime();
mEndZoom = endZoom;
mFinished = false;
mCurrentZoom = 1f;
}
/**
* Computes the current zoom level, returning true if the zoom is still active and false if the
* zoom has finished.
*
* #see android.widget.Scroller#computeScrollOffset()
*/
public boolean computeZoom() {
if (mFinished) {
return false;
}
long tRTC = SystemClock.elapsedRealtime() - mStartRTC;
if (tRTC >= mAnimationDurationMillis) {
mFinished = true;
mCurrentZoom = mEndZoom;
return false;
}
float t = tRTC * 1f / mAnimationDurationMillis;
mCurrentZoom = mEndZoom * mInterpolator.getInterpolation(t);
return true;
}
/**
* Returns the current zoom level.
*
* #see android.widget.Scroller#getCurrX()
*/
public float getCurrZoom() {
return mCurrentZoom;
}
}
Can someone also recommend some great sample about image and gesture handling? From basic to advanced.....Thanks a lot.
The double tap is actually done in InteractiveLineGraphView view itself
#Override
public boolean onDoubleTap(MotionEvent e) {
mZoomer.forceFinished(true);
if (hitTest(e.getX(), e.getY(), mZoomFocalPoint)) {
mZoomer.startZoom(ZOOM_AMOUNT);
}
ViewCompat.postInvalidateOnAnimation(InteractiveLineGraphView.this);
return true;
}
Zoomer is just a helper class holding current zoom level

Make Score Activity

I want to display the score when the quiz game is over.
I make it in two classes.
My code for the score is:
public class Helper {
/**
* This method selects a end game response based on the players score
/**
* Method to return an image to use for the end of game screen
*
* #param numCorrect - number of correct answers
* #param numRounds - number of rounds
*/
public static int getResult(int numCorrect, int numRounds){
//calculate percentage
int percentage = calculatePercentage(numCorrect, numRounds);
return percentage;
}
/**
* Calculate the percentage result based on the number correct and number of questions
*
* #param numCorrect - number of questions right
* #param numRounds - total number of questions
* #return int percentage correct
*/
private static int calculatePercentage(int numCorrect, int numRounds) {
int percentage = numCorrect/numRounds*100;
return percentage;
}
}
and
public class ResultPretest1 extends Activity implements OnClickListener{
TextView txtNilai;
Button tutorial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_pretest1);
GamePlay currentGame = ((BenkyouApplication)getApplication()).getCurrentGame();
int nilai = Helper.getResult(currentGame.getRight(), currentGame.getNumRounds());
txtNilai = (TextView)findViewById(R.id.nilai);
txtNilai.setText(String.valueOf(nilai));
tutorial = (Button) findViewById(R.id.tutorial);
tutorial.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.result, menu);
return true;
}
/*private static int calculatePercentage(final int numCorrect, final int numRounds) {
int score = 0;
score = numCorrect/numRounds*100;
return score;
}*/
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tutorial :
tutorial.setBackgroundResource(R.drawable.tutorial1);
Intent tulv1 = new Intent(this, TutorialLevel1.class);
startActivity(tulv1);
break;
}
}
/* (non-Javadoc)
* #see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
*
* This method is to override the back button on the phone
* to prevent users from navigating back in to the quiz
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
}
But displayed score is always 0. The score did not increase when the answer is right
please help me....
It might have to do with the way you're handling your scores in your Helper. Integer division truncates decimals, so when you have
int percentage = numCorrect/numRounds*100;
Then it will always return 0 unless they got 100% correct. Try using double or float instead of int.
try multiply first as follows:
int percentage = (100*numCorrect)/numRounds;

Image(s) placement over a image in Android Saving memory

I'm placing ImageView's in a RelativeLayout. I'm setting them with LayoutParams and using setMargins() to set the location of each picture. The max number of Images that will be placed on top of the first one will only reach 8. Their are 5 diffident Images and 8 positions on the screen where they can be placed. I would like to create the Images as their corresponding buttons are pressed and to be able to set that Image into the RelativeLayout and display the change. I would like a way to clear all the Images off the screen except for the main/ background ImageView. I don't like to populate 8 X 5 = 40 Images and then hide them all then change their view to Visible when i need them to show. I need something that will populate as need be but able to destory or remove when I clear it out.
Thanks,
Zelda
aButton.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
noteNumber++;
if(noteNumber <= 8){
note n = new note(getBaseContext());
n.setNoteNumber(noteNumber);
n.setHeight(85);
images.add(n); //ArrayList()
}
populate();
}
});
}
public void populate(){
//if(noteNumber < 9){
for(note a : images){
//note a = images.get(noteNumber-1); //images is of type ArrayList<ImageView>()
if(a != null && a.getMasterImage() != null){
int number = a.getNoteNumber();
imageParams.setMargins(25+45*number, a.getHeight(), 20, 360);
frame.addView(a.getMasterImage(),imageParams);
}
}
}
}
public class note {
private int noteNumber;
private int height;
private ImageView masterImage;
public note(Context c){
masterImage = new ImageView(c);
masterImage.setImageResource(R.raw.zelda);
this.noteNumber = 1;
height = 0;
}
/**
* #return the masterImage
*/
public ImageView getMasterImage() {
return masterImage;
}
/**
* #param masterImage the masterImage to set
*/
public void setMasterImage(ImageView masterImage) {
this.masterImage = masterImage;
}
/**
* #return the noteNumber
*/
public int getNoteNumber() {
return noteNumber;
}
/**
* #param noteNumber the noteNumber to set
*/
public void setNoteNumber(int noteNumber) {
this.noteNumber = noteNumber;
}
/**
* #return the height
*/
public int getHeight() {
return height;
}
/**
* #param height the height to set
*/
public void setHeight(int height) {
this.height = height;
}
}

Android: Change activity state when receiving a phone call

A problem came up in my latest android programming project.
The problem is I would like to change Activity that launches when the phone receives a call.
Is it possible to add some text after the contact name when a call is received.
I have search the web for something that could do that, and been looking in the API for hours and I cannot find anything, is it possible with reflection of something like that?
I have made a class that listens to when the phone_state is receiving a call, and I can get the incomming number, but I would like to change the appearance on the screen.
// Thanks in advance
you can,t edit InCallScreen interface. but you can display some Text or whatever above it using toast,
class MyToast ............
package i4nc4mp.myLock.phone;
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.app.INotificationManager;
import android.app.ITransientNotification;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManagerImpl;
import android.widget.TextView;
/**
* A toast is a view containing a quick little message for the user. The toast class
* helps you create and show those.
* {#more}
*
* <p>
* When the view is shown to the user, appears as a floating view over the
* application. It will never receive focus. The user will probably be in the
* middle of typing something else. The idea is to be as unobtrusive as
* possible, while still showing the user the information you want them to see.
* Two examples are the volume control, and the brief message saying that your
* settings have been saved.
* <p>
* The easiest way to use this class is to call one of the static methods that constructs
* everything you need and returns a new Toast object.
*/
public class MyToast {
static final String TAG = "Toast";
static final boolean localLOGV = false;
/**
* Show the view or text notification for a short period of time. This time
* could be user-definable. This is the default.
* #see #setDuration
*/
public static final int LENGTH_SHORT = 0;
/**
* Show the view or text notification for a long period of time. This time
* could be user-definable.
* #see #setDuration
*/
public static final int LENGTH_LONG = 1;
final Handler mHandler = new Handler();
final Context mContext;
final TN mTN;
int mDuration;
int mGravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
int mX, mY;
float mHorizontalMargin;
float mVerticalMargin;
View mView;
View mNextView;
/**
* Construct an empty Toast object. You must call {#link #setView} before you
* can call {#link #show}.
*
* #param context The context to use. Usually your {#link android.app.Application}
* or {#link android.app.Activity} object.
*/
public MyToast(Context context) {
mContext = context;
mTN = new TN();
mY = context.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.toast_y_offset);
}
/**
* Show the view for the specified duration.
*/
public void show() {
if (mNextView == null) {
throw new RuntimeException("setView must have been called");
}
INotificationManager service = getService();
String pkg = mContext.getPackageName();
TN tn = mTN;
try {
service.enqueueToast(pkg, tn, mDuration);
} catch (RemoteException e) {
// Empty
}
}
/**
* Close the view if it's showing, or don't show it if it isn't showing yet.
* You do not normally have to call this. Normally view will disappear on its own
* after the appropriate duration.
*/
public void cancel() {
mTN.myHide();
// TODO this still needs to cancel the inflight notification if any
}
/**
* Set the view to show.
* #see #getView
*/
public void setView(View view) {
mNextView = view;
}
/**
* Return the view.
* #see #setView
*/
public View getView() {
return mNextView;
}
/**
* Set how long to show the view for.
* #see #LENGTH_SHORT
* #see #LENGTH_LONG
*/
public void setDuration(int duration) {
mDuration = duration;
}
/**
* Return the duration.
* #see #setDuration
*/
public int getDuration() {
return mDuration;
}
/**
* Set the margins of the view.
*
* #param horizontalMargin The horizontal margin, in percentage of the
* container width, between the container's edges and the
* notification
* #param verticalMargin The vertical margin, in percentage of the
* container height, between the container's edges and the
* notification
*/
public void setMargin(float horizontalMargin, float verticalMargin) {
mHorizontalMargin = horizontalMargin;
mVerticalMargin = verticalMargin;
}
/**
* Return the horizontal margin.
*/
public float getHorizontalMargin() {
return mHorizontalMargin;
}
/**
* Return the vertical margin.
*/
public float getVerticalMargin() {
return mVerticalMargin;
}
/**
* Set the location at which the notification should appear on the screen.
* #see android.view.Gravity
* #see #getGravity
*/
public void setGravity(int gravity, int xOffset, int yOffset) {
mGravity = gravity;
mX = xOffset;
mY = yOffset;
}
/**
* Get the location at which the notification should appear on the screen.
* #see android.view.Gravity
* #see #getGravity
*/
public int getGravity() {
return mGravity;
}
/**
* Return the X offset in pixels to apply to the gravity's location.
*/
public int getXOffset() {
return mX;
}
/**
* Return the Y offset in pixels to apply to the gravity's location.
*/
public int getYOffset() {
return mY;
}
/**
* Make a standard toast that just contains a text view.
*
* #param context The context to use. Usually your {#link android.app.Application}
* or {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either {#link #LENGTH_SHORT} or
* {#link #LENGTH_LONG}
*
*/
public static MyToast makeText(Context context, CharSequence text, int duration) {
MyToast result = new MyToast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
/**
* Make a standard toast that just contains a text view with the text from a resource.
*
* #param context The context to use. Usually your {#link android.app.Application}
* or {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #param duration How long to display the message. Either {#link #LENGTH_SHORT} or
* {#link #LENGTH_LONG}
*
* #throws Resources.NotFoundException if the resource can't be found.
*/
public static MyToast makeText(Context context, int resId, int duration)
throws Resources.NotFoundException {
return makeText(context, context.getResources().getText(resId), duration);
}
/**
* Update the text in a Toast that was previously created using one of the makeText() methods.
* #param resId The new text for the Toast.
*/
public void setText(int resId) {
setText(mContext.getText(resId));
}
/**
* Update the text in a Toast that was previously created using one of the makeText() methods.
* #param s The new text for the Toast.
*/
public void setText(CharSequence s) {
if (mNextView == null) {
throw new RuntimeException("This Toast was not created with Toast.makeText()");
}
TextView tv = (TextView) mNextView.findViewById(com.android.internal.R.id.message);
if (tv == null) {
throw new RuntimeException("This Toast was not created with Toast.makeText()");
}
tv.setText(s);
}
// =======================================================================================
// All the gunk below is the interaction with the Notification Service, which handles
// the proper ordering of these system-wide.
// =======================================================================================
private static INotificationManager sService;
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
}
private class TN extends ITransientNotification.Stub {
final Runnable mShow = new Runnable() {
public void run() {
handleShow();
}
};
final Runnable mHide = new Runnable() {
public void run() {
handleHide();
}
};
private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
WindowManagerImpl mWM;
TN() {
// XXX This should be changed to use a Dialog, with a Theme.Toast
// defined that sets up the layout params appropriately.
final WindowManager.LayoutParams params = mParams;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = com.android.internal.R.style.Theme_Dialog_Alert;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
}
/**
* schedule handleShow into the right thread
*/
public void show() {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.post(mShow);
}
/**
* schedule handleHide into the right thread
*/
public void hide() {
System.out.println("hide called");
if (localLOGV) Log.v(TAG, "HIDE: " + this);
// mHandler.post(mHide);
}
public void myHide(){
System.out.println("my hide called");
if (localLOGV) Log.v(TAG, "HIDE: " + this);
mHandler.post(mHide);
}
public void handleShow() {
if (localLOGV) Log.v(TAG, "HANDLE SHOW: " + this + " mView=" + mView
+ " mNextView=" + mNextView);
if (mView != mNextView) {
// remove the old view if necessary
handleHide();
mView = mNextView;
mWM = WindowManagerImpl.getDefault();
final int gravity = mGravity;
mParams.gravity = gravity;
if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
mParams.horizontalWeight = 1.0f;
}
if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
mParams.verticalWeight = 1.0f;
}
mParams.x = mX;
mParams.y = mY;
mParams.verticalMargin = mVerticalMargin;
mParams.horizontalMargin = mHorizontalMargin;
if (mView.getParent() != null) {
if (localLOGV) Log.v(
TAG, "REMOVE! " + mView + " in " + this);
mWM.removeView(mView);
}
if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this);
mWM.addView(mView, mParams);
}
}
public void handleHide() {
//System.out.println("handle hid ecalles");
if (localLOGV) Log.v(TAG, "HANDLE HIDE: " + this + " mView=" + mView);
if (mView != null) {
// note: checking parent() just to make sure the view has
// been added... i have seen cases where we get here when
// the view isn't yet added, so let's try not to crash.
if (mView.getParent() != null) {
if (localLOGV) Log.v(
TAG, "REMOVE! " + mView + " in " + this);
mWM.removeView(mView);
}
mView = null;
}
}
}
}
// in broadcaste receiver ..........
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE)
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
toast = new MyToast(context);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(view);
toast.show();
}
else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
toast.cancel();
}
else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
toast.cancel();
}
}

Categories

Resources