Paint with Java - java

So I need do one app in Android Studio like Paint
I have this in Myview.Java.
I obtain the coordinates but I can´t save and draw the segment.
I tried with a Vector and I thing Vector is a solution, but isn´t working like I did
public class MyView extends View {
Paint paint = null;
int figure;
public MyView(Context context) {
super(context);
paint = new Paint();
figure = 0;
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
figure = 0;
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
figure = 0;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
if (figure == 1)
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
public void setfigure(int a) {
this.figure = a;
}
}
In MainActivity I have this code
public class MainActivity extends AppCompatActivity {
MyView v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v = findViewById(R.id.teste);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
//String x1 = "" + x;
TextView textView = (TextView) findViewById(R.id.testecord);
TextView textView2 = (TextView) findViewById(R.id.testecord2);
Ponto2D pinicial = new Ponto2D(Math.round(x), Math.round(y));
Ponto2D pfinal = new Ponto2D(Math.round(x), Math.round(y));
String x1 = "" + pinicial.x;
String x2 = "" + pfinal.x;
textView.setText(x1);
textView2.setText(x2);
int n = 4; // tamanho do vetor
int v[] = new int[n]; // declaração e alocação de espaço para o vetor "v"
int i; // índice ou posição
// processando os "n" elementos do vetor "v"
for (i = 0; i < n; i++) {
v[i] = pinicial.x; // na i-ésima posição do vetor "v" armazena o valor da variável "i"
}
return true;
}
public void f(View vs) {
v.setfigure(1);
v.invalidate();
}
}
I need save the points who user click to draw one straight segment.
I have the code of segment and of Point.
public class Segmento_de_Reta {
Ponto2D pinicial;
Ponto2D pfinal;
String cor;
public Segmento_de_Reta(Ponto2D a, Ponto2D b) {
pinicial = a;
pfinal = b;
}

Related

In Android change a Method from Void to Return?

I'm creating a game in which I'm drawing a path that starts at the center x,y coordinates of a RelativeLayout. I'm getting the x,y coordinates, but I can't figure out how to pass the coordinates into the Path Drawing Class using my getNumbers() method. I've got this bit in the onCreate:
getNumbers();
path_em = new PathEM(this, xTint, yTint);
gBoard_RL.addView(path_em);
root_RL.addView(gBoard_RL);
and here's getNumbers():
public void getNumbers() {
gBoard_RL.getViewTreeObserver().addOnGlobalLayoutListener(NumbersoGLL);
}
OnGlobalLayoutListener NumbersoGLL = new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
xRLWInt = gBoard_RL.getWidth() / 2;
yRLHInt = gBoard_RL.getHeight() / 2;
xTint = gBoard_RL.getLeft() + xRLWInt;
yTint = gBoard_RL.getTop() + yRLHInt;
}
};
I think I have to rewrite getNumbers() so that's it's not void, but returns xTint and yTint, right? I don't know how to do that because public void onGlobalLayout() can't be changed to pass an int, when I try I get an error saying that it HAS to be void.
So basically, what I'm trying to do is in the onCreate of Game3 Class I need to get the center coordinate integers, then pass them into my Path Drawing Class. Here's the entire Game 3 Class:
public class Game3 extends Activity {
PathEM path_em;
RelativeLayout root_RL, gBoard_RL, startTimer_RL;
LayoutParams root_LP, startTimer_LP, gBoardInfo_LP, gBoard_LP, rootStartTimer_LP;
LayoutInflater LayInf = null;
View root_VUE, gBoardInfo_VUE;
TextView gameScore_TV, gameTime_TV, readyCD_TV;
FrameLayout root_FrameL;
int xScrInt, yScrInt, xRLWInt, yRLHInt, xTint, yTint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.cutin, R.anim.cutout);
// -- Create Root Layout
root_RL = new RelativeLayout(this);
root_LP = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
root_RL.setId(1);
root_RL.setBackgroundColor(Color.WHITE);
root_RL.setLayoutParams(root_LP);
// --- END Create Root Layout
// --- Create GameBoard
LayInf = (LayoutInflater) getApplicationContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
gBoardInfo_VUE = LayInf.inflate(R.layout.game1_info, null);
gBoardInfo_LP = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
gBoardInfo_LP.addRule(RelativeLayout.ALIGN_PARENT_TOP,
RelativeLayout.TRUE);
gBoardInfo_VUE.setId(2);
gBoardInfo_VUE.setLayoutParams(gBoardInfo_LP);
gameTime_TV = (TextView) gBoardInfo_VUE
.findViewById(R.id.game1_timeValue2_TV);
gameScore_TV = (TextView) gBoardInfo_VUE
.findViewById(R.id.game1_scoreValue2_TV);
root_RL.addView(gBoardInfo_VUE);
gBoard_RL = new RelativeLayout(this);
gBoard_LP = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
gBoard_LP.addRule(RelativeLayout.BELOW, gBoardInfo_VUE.getId());
gBoard_LP.setMargins(10, 10, 10, 10);
gBoard_RL.setLayoutParams(gBoard_LP);
gBoard_RL.setBackgroundColor(Color.BLUE);
//--- add stuff here
getNumbers();
path_em = new PathEM(this, xTint, yTint);
gBoard_RL.addView(path_em);
root_RL.addView(gBoard_RL);
root_FrameL = new FrameLayout(this);
root_FrameL.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
root_FrameL.addView(root_RL);
setContentView(root_FrameL);
// --- END Create GameBoard
}//--- END onCreate
public void getNumbers() {
gBoard_RL.getViewTreeObserver().addOnGlobalLayoutListener(NumbersoGLL);
}
OnGlobalLayoutListener NumbersoGLL = new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
xRLWInt = gBoard_RL.getWidth() / 2;
yRLHInt = gBoard_RL.getHeight() / 2;
xTint = gBoard_RL.getLeft() + xRLWInt;
yTint = gBoard_RL.getTop() + yRLHInt;
}
};
//--- PathEM Class
public class PathEM extends View {
Paint paint = new Paint();
Path path = new Path();
public PathEM(Context context, int xTint, int yTint){
super(context);
}
Pt[] thePath = { new Pt(xTint, yTint),
new Pt(200, 200),
new Pt(200, 500),
new Pt(400, 500)
};
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.GREEN);
paint.setStrokeWidth(7);
paint.setStyle(Paint.Style.STROKE);
path.moveTo(thePath[0].x, thePath[0].y);
for (int i = 1; i < thePath.length; i++) {
path.lineTo(thePath[i].x, thePath[i].y);
}
canvas.drawPath(path, paint);
}// --- END onDraw
class Pt {
float x, y;
Pt(float _x, float _y) {
x = _x;
y = _y;
}
}
}
}
You should put the code where you initialize the PathEM object in the onGlobalLayout() Method.
Like this:
OnGlobalLayoutListener NumbersoGLL = new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
xRLWInt = gBoard_RL.getWidth() / 2;
yRLHInt = gBoard_RL.getHeight() / 2;
xTint = gBoard_RL.getLeft() + xRLWInt;
yTint = gBoard_RL.getTop() + yRLHInt;
path_em = new PathEM(this, xTint, yTint);
gBoard_RL.addView(path_em);
root_RL.addView(gBoard_RL);
}
};
How about creating a Constants Class and setting the variable of contants variable in your onGlobalLayout() method.
That way you need not do any return.
public class Constants {
public static int value1=0;
public static int value2=0;
public static int value3=0;
public static int value4=0;
}
In your onGlobalLayout() method
Constants.value1= gBoard_RL.getWidth() / 2;
Constants.value2= gBoard_RL.getHeight() / 2;
Constants.value3= gBoard_RL.getLeft() + xRLWInt;
Constants.value4= gBoard_RL.getTop() + yRLHInt;

SherlockActionBar NullPointerException

I'm working on an android app that is a hearing test. it was quite outdated so I've had to update it. I've used the Sherlock library so the app is compatible for many different phones. What I'm trying to do is get the results of a hearing test to show up. The problem I'm getting it when I draw the graph to show the user how well they did, I'm getting a null pointer exception.
once the test is completed, the user is taken to the Saved tests Activity shown below:
public class SavedResultsActivity extends SherlockListActivity {
// TODO set column names when saving test implemented
private static final String TEST_NAME_COLUMN = ResultsDatabase.SAVED_NAME;
private static final String TEST_DATE_COLUMN = ResultsDatabase.COLUMN_NAME_CREATE_DATE;
private ResultsDatabase mDb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDb = new ResultsDatabase(this);
setContentView(R.layout.saved_tests);
ActionBar ab = getSherlock().getActionBar();
SherlockHelper.setupActionBar(ab, this);
TextView titleText = (TextView)findViewById(R.id.title_text);
titleText.setText(R.string.Saved_Tests);
// Set the empty view
getListView().setEmptyView(findViewById(R.id.empty));
getListView().setItemsCanFocus(true);
// Get a cursor with all phones
Cursor c = getSavedTests();
if ( c != null ) {
// Set up our adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.saved_results_item, c,
new String[] { TEST_NAME_COLUMN, TEST_DATE_COLUMN, TEST_DATE_COLUMN },
new int[] { android.R.id.text1, android.R.id.text2, R.id.delete_button });
adapter.setViewBinder(mViewBinder);
// Set up our adapter
setListAdapter(adapter);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
Intent intent = new Intent(this, TabbedResults.class);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
intent.putExtra(ResultsDatabase._ID, cursor.getInt(cursor.getColumnIndex(ResultsDatabase._ID)));
startActivity(intent);
}
private final ViewBinder mViewBinder = new SimpleCursorAdapter.ViewBinder(){
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if ( view.getId() == android.R.id.text1 ){
String name = cursor.getString(columnIndex);
TextView nameView = (TextView)view;
nameView.setText(name);
} else if ( view.getId() == android.R.id.text2 ){
long date = cursor.getLong(columnIndex);
String dateStr = DateUtils.formatDateTime(view.getContext(), date, DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE);
TextView dateView = (TextView)view;
dateView.setText(dateStr);
} else if ( view.getId() == R.id.delete_button ){
int idCol = cursor.getColumnIndex(ResultsDatabase._ID);
final long id = cursor.getLong(idCol);
view.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View v) {
deleteTest(id);
}
});
}
return true;
}
};
private static final String DELETE_SELECTION = ResultsDatabase._ID + " = ? ";
private void deleteTest(long id) {
String[] whereArgs = new String[]{String.valueOf(id)};
SQLiteDatabase db = mDb.getWritableDatabase();
db.delete(ResultsDatabase.TABLE_NAME, DELETE_SELECTION, whereArgs);
SimpleCursorAdapter adapter = (SimpleCursorAdapter) getListAdapter();
adapter.getCursor().requery();
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
// TODO fetch list of saved tests
private Cursor getSavedTests(){
// get cursor
SQLiteDatabase db = mDb.getReadableDatabase();
Cursor c = db.query(ResultsDatabase.TABLE_NAME, null, null, null, null, null,null);
startManagingCursor(c);
return c;
}
}
Here the user will click on the test they want to view and that will take the user to a tabbed results page one tab for one ear the other tab for the other ear. I've used fragments for this:
public class TabbedResults extends SherlockFragmentActivity{
TabHost mTabHost;
TabManager mTabManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_indicator);
ActionBar ab = this.getSupportActionBar();
SherlockHelper.setupActionBar(ab, this);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
mTabManager.addTab(mTabHost.newTabSpec(getString(R.string.Left_ear)).setIndicator(getString(R.string.Left_ear)),
ResultActivity.Results.class, null);
mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator(getString(R.string.Left_ear)),
ResultActivity.Results.class, null);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
}
this method uses another method called TabManager to manage which tab is open etc:
public class TabManager extends SherlockFragmentActivity implements TabHost.OnTabChangeListener {
private final FragmentActivity mActivity;
private final TabHost mTabHost;
private final int mContainerId;
private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
TabInfo mLastTab;
static final class TabInfo {
private final String tag;
private final Class<?> clss;
private final Bundle args;
private Fragment fragment;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
mActivity = activity;
mTabHost = tabHost;
mContainerId = containerId;
mTabHost.setOnTabChangedListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mActivity));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
if (info.fragment != null && !info.fragment.isDetached()) {
FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
ft.detach(info.fragment);
ft.commit();
}
mTabs.put(tag, info);
mTabHost.addTab(tabSpec);
}
#Override
public void onTabChanged(String tabId) {
TabInfo newTab = mTabs.get(tabId);
if (mLastTab != newTab) {
FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
if (mLastTab != null) {
if (mLastTab.fragment != null) {
ft.detach(mLastTab.fragment);
}
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(mActivity,
newTab.clss.getName(), newTab.args);
ft.add(mContainerId, newTab.fragment, newTab.tag);
} else {
ft.attach(newTab.fragment);
}
}
mLastTab = newTab;
ft.commit();
mActivity.getSupportFragmentManager().executePendingTransactions();
}
}
private Intent createIntent( boolean aRight) {
Intent newIntent = new Intent(getIntent());
newIntent.putExtra(ResultActivity.IS_RIGHT_EAR, aRight);
newIntent.setClass(this, ResultActivity.class);
return newIntent;
}
}
So the activity used to show the results of each ear is the results activity:
public class ResultActivity extends SherlockFragmentActivity {
public static final String IS_RIGHT_EAR = "is_right_ear";
private ArrayList<EarSrt> leftAnswerList;
private ArrayList<EarSrt> rightAnswerList;
private boolean isRightEarTab = true;
private boolean bothEarsBad;
private boolean leftEarBad;
private boolean rightEarBad;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Intent intent = getIntent();
int rowId = intent.getIntExtra(ResultsDatabase._ID, -1);
if ( rowId != -1 ) {
ResultsDatabase db = new ResultsDatabase(this);
String select = "(" + ResultsDatabase._ID + " == " + rowId + ")";
Cursor c = db.getReadableDatabase().query(ResultsDatabase.TABLE_NAME, null, select, null, null, null,null);
if ( c.moveToFirst() ) {
int leftEarColumn = c.getColumnIndex(ResultsDatabase.LEFT_EAR);
byte[] leftEarByteArray = c.getBlob(leftEarColumn);
int rightEarColumn = c.getColumnIndex(ResultsDatabase.RIGHT_EAR);
byte[] rightEarByteArray = c.getBlob(rightEarColumn);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
} else {
byte[] leftEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.LEFT_EAR);
byte[] rightEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.RIGHT_EAR);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
isRightEarTab = getIntent().getBooleanExtra(IS_RIGHT_EAR, true);
setResults(leftAnswerList, rightAnswerList);
if (savedInstanceState == null) {
// Do first time initialization -- add initial fragment.
Fragment newFragment = new Results();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.resultsContainer, newFragment).commit();
}
}
private float calculateAverage(List<EarSrt> steps) {
float srt = 0.0f;
int length = steps.size();
for (int i = (int)Math.ceil( (float)length/(float)2); i < length; i++) {
EarSrt es = steps.get(i);
srt += es.getSrt();
//printf("%f ," , [es srt]);
}
srt = srt / (length-(float)Math.ceil( (float)length/(float)2));
// printf("\n%f\n" , srt);
return srt;
}
private void setResults(List<EarSrt> leftEar, List<EarSrt> rightEar) {
float esLeft = calculateAverage(leftEar);
float esRight = calculateAverage(rightEar);
leftEarBad = (esLeft > 24.0);
rightEarBad = (esRight > 24.0);
bothEarsBad = (leftEarBad && rightEarBad);
setResultCaption(bothEarsBad, leftEarBad, rightEarBad);
}
/**
* TODO: this needs finishing
*/
private void setResultCaption(boolean bothEarsBad, boolean leftEarBad, boolean rightEarBad) {
TextView resultsTextView = (TextView)findViewById(R.id.results_text);
StringBuilder resultsText = new StringBuilder();
if (bothEarsBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else{
if (leftEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_left_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
} else if (rightEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_Right_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else {
resultsText.append(getString(R.string.There_is_no_indication_of_hearing_loss));
}
}
resultsText.append(getString(R.string.The_results_of_the__hearing_test_are_not_to_be_utilized_as_an_official_outcome_for_assessing_levels_of_hearing_loss_True_hearing_loss_assessments_can_only_be_determined_by_a_licensed_hearing_healthcare_provider));
resultsTextView.setText(resultsText.toString());
}
public void goToLocate(View aView){
Intent locate = new Intent( this, MapActivity.class);
startActivity(locate);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
public static class Results extends SherlockFragment{
// #Override
// public void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
//
// }
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.results_layout, container, false);
return rootView;
}
}
}
Now this class uses the GraphView class to draw the graph:
public final class GraphView extends View {
private static final float SCALE = 0.008f; // map (min,max) to ( 0, 1)
private static final float WIDTH = 0.02f; // map (min,max) to ( 0, 1)
ArrayList<EarSrt> mPoints;
// drawing tools
private RectF rimRect;
private RectF rimRectTop;
private RectF rimRectBottom;
private float[] centreLine;
private RectF topSideBar;
private RectF bottomSideBar;
private Paint rimPaintTop;
private Paint rimPaintBottom;
private Paint outerRimPaint;
private Paint centreLinePaint;
private Paint topSideBarPaint;
private Paint bottomSideBarPaint;
private Paint titlePaint;
private Paint keyPaint;
private Paint correctPointPaint;
private Paint incorrectPointPaint;
private Paint linePaint;
private Paint pointOutlinePaint;
private Paint averagePaint;
private Paint backgroundPaint;
// end drawing tools
private Bitmap background; // holds the cached static part
private float mAverage;
public GraphView(Context context) {
super(context);
init();
}
public GraphView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GraphView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
initDrawingTools();
}
private String getTitle() {
return getContext().getString(R.string.Normal_hearing);
}
private void initDrawingTools() {
rimRect = new RectF(0.0f, 0.0f, 1.0f, 1.0f);
rimRectTop = new RectF(0.0f, 0.5f, 1.0f, 1.0f);
rimRectBottom = new RectF(0.0f, 0.0f, 1.0f, 0.5f);
centreLine = new float[4];
centreLine[0]=0.0f;
centreLine[1]=0.5f;
centreLine[2]=1.0f;
centreLine[3]=0.5f;
topSideBar = new RectF(0.95f, 0.5f, 1.0f, 1.0f);
bottomSideBar = new RectF(0.95f, 0.0f, 1.0f, 0.5f);
// the linear gradient is a bit skewed for realism
rimPaintTop = new Paint();
rimPaintTop.setFlags(Paint.ANTI_ALIAS_FLAG);
rimPaintTop.setShader(new LinearGradient(0.40f, 0.0f, 0.60f, 1.0f,
0xff9ea3ac,
0xffc0c2c6,
TileMode.CLAMP));
rimPaintBottom = new Paint();
rimPaintBottom.setFlags(Paint.ANTI_ALIAS_FLAG);
rimPaintBottom.setShader(new LinearGradient(0.40f, 0.0f, 0.60f, 1.0f,
0xffc5cbbd,
0xff3d4649,
TileMode.CLAMP));
outerRimPaint = new Paint();
outerRimPaint.setAntiAlias(true);
outerRimPaint.setStyle(Paint.Style.STROKE);
outerRimPaint.setColor(Color.argb(0x4f, 0x33, 0x36, 0x33));
outerRimPaint.setStrokeWidth(0.001f);
centreLinePaint = new Paint();
centreLinePaint.setStyle(Paint.Style.STROKE);
centreLinePaint.setColor(0xff90cc38);
centreLinePaint.setAntiAlias(true);
centreLinePaint.setStrokeWidth(0.02f);
topSideBarPaint = new Paint();
topSideBarPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
topSideBarPaint.setShader(new LinearGradient(0.40f, 0.0f, 0.60f, 1.0f,
0xffc5cbbd,
0xff3d4649,
TileMode.CLAMP));
bottomSideBarPaint = new Paint();
bottomSideBarPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
bottomSideBarPaint.setShader(new LinearGradient(0.40f, 0.0f, 0.60f, 1.0f,
0xff4c9b3e,
0xffa0dd61,
TileMode.CLAMP));
titlePaint = new Paint();
titlePaint.setColor(0xffffffff);
titlePaint.setAntiAlias(true);
titlePaint.setTypeface(Typeface.DEFAULT_BOLD);
titlePaint.setTextAlign(Paint.Align.CENTER);
titlePaint.setTextSize(0.05f);
titlePaint.setTextScaleX(0.8f);
keyPaint = new Paint();
keyPaint.setColor(0xff000000);
keyPaint.setAntiAlias(true);
keyPaint.setTypeface(Typeface.DEFAULT_BOLD);
keyPaint.setTextAlign(Paint.Align.LEFT);
keyPaint.setTextSize(0.05f);
keyPaint.setTextScaleX(0.8f);
backgroundPaint = new Paint();
backgroundPaint.setFilterBitmap(true);
linePaint = new Paint();
linePaint.setColor(0xffffffff);
linePaint.setStrokeWidth(0);
averagePaint = new Paint();
averagePaint.setColor(0xff000000);
averagePaint.setStyle(Paint.Style.FILL);
correctPointPaint = new Paint();
correctPointPaint.setColor(0xff90cc38);
correctPointPaint.setStyle(Paint.Style.FILL);
incorrectPointPaint = new Paint();
incorrectPointPaint.setColor(0xffb1b3ba);
correctPointPaint.setStyle(Paint.Style.FILL);
pointOutlinePaint = new Paint();
pointOutlinePaint.setStyle(Paint.Style.STROKE);
pointOutlinePaint.setColor(0xffffffff);
pointOutlinePaint.setAntiAlias(true);
pointOutlinePaint.setStrokeWidth(0.0f);
}
private void drawRim(Canvas canvas) {
// first, draw the metallic body
canvas.drawRect(rimRectTop, rimPaintTop);
canvas.drawRect(rimRectBottom, rimPaintBottom);
// now the outer rim circle
canvas.drawRect(rimRect, outerRimPaint);
// Draw middleline
canvas.drawLines(centreLine, centreLinePaint);
// Draw sidebars
canvas.drawRect(topSideBar, topSideBarPaint);
canvas.drawRect(bottomSideBar, bottomSideBarPaint);
}
public void setPoints( ArrayList<EarSrt> aPoints){
mPoints = aPoints;
}
private void drawTitle(Canvas canvas) {
String title = getTitle();
canvas.drawText(title, 0.2f, 0.1f, titlePaint);
}
private void drawBackground(Canvas canvas) {
if (background == null) {
} else {
canvas.drawBitmap(background, 0, 0, backgroundPaint);
}
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = (int)(width * 0.8f);
setMeasuredDimension(width, height);
}
#Override
protected void onDraw(Canvas canvas) {
drawBackground(canvas);
canvas.restore();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
regenerateBackground();
}
private void regenerateBackground() {
// free the old bitmap
if (background != null) {
background.recycle();
}
background = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas backgroundCanvas = new Canvas(background);
float scaleWidth = (float) getWidth();
float scaleHeight = (float) getHeight();
backgroundCanvas.scale(scaleWidth, scaleHeight/1.23f);
drawRim(backgroundCanvas);
drawTitle(backgroundCanvas);
drawPoints(backgroundCanvas);
drawKey(backgroundCanvas);
}
private void drawPoints(Canvas canvas) {
float gap = 1.0f/((float)mPoints.size()+2);
// Iterate though the points twice, once to
// draw the line and one to draw the points
// doesn't appear to be the most efficient
// method, but calculations of point size etc
// Draw line
int count = 1;
float prev_x = 0.0f;
float prev_y = 0.0f;
for ( EarSrt vo : mPoints){
float y_pos = 0.5f + 2*( vo.getSrt() - 24.0f)*SCALE;
float x_pos = gap*count;
if ( count != 1 ){
canvas.drawLine(prev_x, prev_y, x_pos, y_pos, linePaint);
}
count++;
prev_x = x_pos;
prev_y = y_pos;
}
// draw points
count = 1;
for ( EarSrt vo : mPoints){
float y_pos = 0.5f + 2*( vo.getSrt() - 24.0f)*SCALE;
float x_pos = gap*count;
count++;
RectF rect = new RectF(x_pos - WIDTH, y_pos - WIDTH, x_pos + WIDTH, y_pos + WIDTH);
if ( vo.isCorrect() ) {
canvas.drawRect(rect, correctPointPaint);
} else {
canvas.drawRect(rect, incorrectPointPaint);
}
canvas.drawRect(rect, pointOutlinePaint);
}
// Plot average line
float yAverage = 0.5f + 2*( mAverage - 24.0f)*SCALE;
RectF averageRect = new RectF(0.95f, yAverage - WIDTH/2.0f, 1.0f, yAverage + WIDTH/2.0f);
canvas.drawRect(averageRect, averagePaint);
}
private void drawKey(Canvas canvas) {
float rightEdge = 0.05f;
float leftEdge = 0.05f + 4 * WIDTH;
// Example correct square
RectF rect = new RectF(rightEdge, 1.1f - WIDTH, rightEdge + 2 * WIDTH, 1.1f + WIDTH);
canvas.drawRect(rect, correctPointPaint);
canvas.drawRect(rect, pointOutlinePaint);
String correctResults = getContext().getString(R.string.Correct_results);
canvas.drawText(correctResults, leftEdge, 1.1f + WIDTH, keyPaint);
// Test result line
RectF averageRect = new RectF(rightEdge, 1.2f - WIDTH/2.0f, rightEdge + 2 * WIDTH, 1.2f + WIDTH/2.0f);
canvas.drawRect(averageRect, averagePaint);
String testResults = getContext().getString(R.string.Your_test_result);
canvas.drawText(testResults, leftEdge, 1.2f + WIDTH/2.0f, keyPaint);
}
public void setAverage(float aAverage) {
mAverage = aAverage;
}
}
the issues I'm getting are on the GraphView class in the drawPoints, regenerateBackground and onSizeChanged methods.
Another issue I have is showing the correct information in the correct tab. So for one tab it only shows the results from the left are and vice versa. Any help on these issues would be massively grateful as I've been trying to get this to work for ages!!
Thanks again for any help thats given.

Unable to hide IndexScroll from listview

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
}

custom ondraw method is not working

I am working on application in which i want to display different text on image.when i touch the different position.I am working on the different image.In my program I have used one class to change the image and one class to draw a text on the image.
my activity class is as follow......
public class VideosActivity extends Activity implements OnTouchListener
{
//DrawView draw;
float a=0;
float b=0;
ImageView image;
MotionEvent event;
Button back ;
Button next;
TextView t;
String info = "";
int count =0;
FirstImage i;
ViewFlipper c;
Infoview v;
String huma="human";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_layout);
i=new FirstImage(this);
c=(ViewFlipper) findViewById(R.id.viewFlipper1);
back = (Button) findViewById(R.id.button1);
next = (Button) findViewById(R.id.button2);
t=(TextView) findViewById(R.id.textView1);
if(count==0)
i.changeImage(R.drawable.human );
i.invalidate();
c.addView(i,0);
c.setOnTouchListener(this);
c.onTouchEvent(event);
}
public void pageinfo(float a,float b)
{
t.setText(Float.toString(a)+"x"+Float.toString(b)+"y");
i.display( a, b);
}
public boolean onTouch(View v, MotionEvent me)
{
// TODO Auto-generated method stub
switch(me.getAction())
{
case MotionEvent.ACTION_DOWN:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_MOVE:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_UP:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_OUTSIDE:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
default: return false;
}
return true;
}
}
the class which is used to change the image is as follow...
public class FirstImage extends LinearLayout {
ImageView i;
int x;
Infoview v;
String huma ="human";
public FirstImage(Context context) {
super(context);
v=new Infoview(context);
i= new ImageView (context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
addView(i, lp);
addView(v,lp);
}
public FirstImage(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void changeImage(int id){
i.setImageResource(id);
x=id;
}
public int getSrc() {
// TODO Auto-generated method stub
return x;
}
public void display(float a, float b) {
// TODO Auto-generated method stub
if(i.getId()==R.drawable.human){
v.updateInfo(huma, a, b);
i.invalidate();
v.invalidate();
}
}
}
class which is used for drawing text on the image is as follow..
public class Infoview extends View {
String info = "";
float x = 0; //init value
float y = 0; //init value
int color = Color.WHITE;
public Infoview(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public Infoview(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public Infoview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setColor(color);
paint.setStrokeWidth(2);
paint.setTextSize(30);
canvas.drawLine(x-10, y, x+10, y, paint);
canvas.drawLine(x, y-10, x, y+10, paint);
canvas.drawText(info, x, y, paint);
}
public void updateInfo(String t_info, float t_x, float t_y){
info = t_info;
x = t_x;
y = t_y;
invalidate();
}
public void clearInfo(){
info = "";
x = 0;
y = 0;
invalidate();
}
I am not understanding why it is not displaying text on the image ......I think in the time of image drawing i am using one layout.so i have to include drawing class(Infoview) into that layout to...
If any one thinking that i am re asking this question then i am sorry ...
any help is appreciated...
I did get time to read the full code but if you override onDraw, you are not supposed to invoke super.onDraw() inside that method since that will mean that the base class will draw everything first.

how to use Double Tap event in android canvas to save current Image

I have Class which Extends View I'm able To Move one Image Over another For This I use Two Bitmap Image one Over Another now i want to save image's using Double Tap event but i dnt know how to do this....can anyone have some idea or code for this ......
`public class ShowCanvas extends View {
Bitmap CanvasBitmap;
Bitmap ScaledBitmap;
Bitmap smallbitmap;
private static final int INVALID_POINTER_ID = -1;
private Drawable mImage;
private float mPosX;
private float mPosY;
private float mLastTouchX;
private float mLastTouchY;
private int mActivePointerId = INVALID_POINTER_ID;
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
public ShowCanvas(Context context) {
this(context, null, 0);
// TODO Auto-generated constructor stub
ScaledBitmap = DrawView.scaled;
mImage = new BitmapDrawable(getResources(), Dress.bitmap);
System.out.println("MImage" +mImage);
mImage.setBounds(0, 0, mImage.getIntrinsicWidth(),
mImage.getIntrinsicHeight());
}
public ShowCanvas(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ShowCanvas(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
public void setBitmap(Bitmap bitmap) {
// TODO Auto-generated method stub
CanvasBitmap = bitmap;
System.out.println("CanvasBitmap" + CanvasBitmap);
int X = CanvasBitmap.getHeight();
int Y = CanvasBitmap.getWidth();
System.out.println("CanvasBitmap " + X + "\t" + Y);
}
#Override
public boolean isLongClickable() {
// TODO Auto-generated method stub
System.out.println("ISLongClickable");
return super.isLongClickable();
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
// Only move if the ScaleGestureDetector isn't processing a
// gesture.
if (!mScaleDetector.isInProgress()) {
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
invalidate();
}
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
break;
}
}
return true;
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint mpaint = new Paint();
canvas.save();
canvas.drawBitmap(ScaledBitmap, 0, 0, mpaint);
Log.d("DEBUG", "X: " + mPosX + " Y: " + mPosY);
canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor);
mImage.draw(canvas);
canvas.restore();
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
invalidate();
return true;
}
}
}`
If you mean double tap you have to use GestureDetector.OnDoubleTapListener. check this link
try this
public class MyView extends View {
GestureDetector gestureDetector;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// creating new gesture detector
gestureDetector = new GestureDetector(context, new GestureListener());
}
// skipping measure calculation and drawing
// delegate the event to the gesture detector
#Override
public boolean onTouchEvent(MotionEvent e) {
return gestureDetector.onTouchEvent(e);
}
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent e) {
return true;
}
// event when double tap occurs
#Override
public boolean onDoubleTap(MotionEvent e) {
float x = e.getX();
float y = e.getY();
Log.d("Double Tap", "Tapped at: (" + x + "," + y + ")");
return true;
}
}
}

Categories