Android: Speed up dynamic UI generation - android

I have the following class which generates a calendar view. I'm not too fond of the built-in one, and am trying to gain more control over its appearance. However rendering the new UI (e.g. upon swipe) is taking 1-2 seconds to draw. Is there any place I could speed this up? Am testing on HTC One S (2012 model)
Should be relatively straightforward to follow:
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.joda.time.LocalDate;
import java.util.ArrayList;
public class Calendar extends AppCompatActivity {
private LocalDate _currentSelectedDate = new LocalDate();;
private LocalDate _today = new LocalDate();;
private float x1 = 0;
private float x2 = 0;
private float y1 = 0;
private float y2 = 0;
private TableLayout _tableLayout;
private RelativeLayout _relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
_relativeLayout = (RelativeLayout) findViewById(R.id.calendarLayout);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
#Override
public boolean onTouchEvent(MotionEvent touchevent)
{
switch (touchevent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP:
{
x2 = touchevent.getX();
y2 = touchevent.getY();
// up
if (y1 > y2)
{
_currentSelectedDate = _currentSelectedDate.plusMonths(1);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
// down
if (y1 < y2)
{
_currentSelectedDate = _currentSelectedDate.minusMonths(1);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
break;
}
}
return false;
}
private void recreateUI(int year, int month)
{
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
_tableLayout = new TableLayout(this);
_tableLayout.setLayoutParams(lp);
_tableLayout.setStretchAllColumns(true);
_relativeLayout.removeAllViews();
_relativeLayout.addView(_tableLayout);
LocalDate date = new LocalDate().withYear(year).withMonthOfYear(month).dayOfMonth().withMinimumValue();
LocalDate last = date.dayOfMonth().withMaximumValue();
addMonthNameToUi(date);
addDaysNamesToUi();
addDayNumberssToUi(date, last);
}
private void addMonthNameToUi(LocalDate date) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT);
params.span = 7;
TextView t = new TextView(this);
t.setLayoutParams(params);
t.setGravity(Gravity.CENTER);
t.setTypeface(null, Typeface.BOLD);
t.setText(date.toString("MMM yyyy"));
row.addView(t);
float d = getResources().getDisplayMetrics().density;
int margin = (int)(20 * d);
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) t.getLayoutParams();
mlp.setMargins(mlp.leftMargin, mlp.topMargin, mlp.rightMargin, margin);
_tableLayout.addView(row);
}
private void addDaysNamesToUi() {
TableRow dayNameRow = new TableRow(this);
addMonth(dayNameRow, "Mon");
addMonth(dayNameRow, "Tue");
addMonth(dayNameRow, "Wed");
addMonth(dayNameRow, "Thu");
addMonth(dayNameRow, "Fri");
addMonth(dayNameRow, "Sat");
addMonth(dayNameRow, "Sun");
_tableLayout.addView(dayNameRow);
}
private void addDayNumberssToUi(LocalDate date, LocalDate last) {
TableRow row = null;
int columnsCount = 0;
boolean firstRow = true;
while (date.isBefore(last) || date.isEqual(last)) {
if (columnsCount == 0) {
row = new TableRow(this);
_tableLayout.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT, 1.0f));
// blank columns for days not at the start of month
if (firstRow) {
firstRow = false;
int i = 1;
for (; i < date.getDayOfWeek(); i++) {
addDayNumberToRow(row, date, "");
}
columnsCount += i - 1;
date.plusDays(i - 1);
}
}
addDayNumberToRow(row, date, String.valueOf(date.getDayOfMonth()));
date = date.plusDays(1);
columnsCount++;
if (columnsCount == 7)
columnsCount = 0;
}
while (row.getChildCount() < 7)
addDayNumberToRow(row, date, "");
}
private void addMonth(TableRow row, String month)
{
TextView t = new TextView(this);
t.setText(month);
t.setGravity(Gravity.CENTER);
t.setTypeface(null, Typeface.BOLD);
row.addView(t);
}
private void addDayNumberToRow(TableRow row, final LocalDate date, String text)
{
TextView v = new TextView(this);
v.setText(text);
v.setGravity(Gravity.CENTER);
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, 1.0f));
if (date.getDayOfMonth() == _today.getDayOfMonth() && date.getMonthOfYear() == _today.getMonthOfYear() && date.getYear() == _today.getYear()) {
v.setTypeface(v.getTypeface(), Typeface.BOLD);
v.setTextSize(v.getTextSize() + 1);
}
ShapeDrawable border = new ShapeDrawable(new RectShape());
border.getPaint().setStyle(Paint.Style.STROKE);
border.getPaint().setColor(Color.BLACK);
v.setBackground(border);
row.addView(v);
}
}

Your "recreateUI" method do alot of stuff like creating new views. Avoid creating new objects by reusing those already created.
Usually calendar views are quite complex. You most likely wont achieve smooth framerate by using multiple views in such way. You would have to write custom view witch will draw itself.

Turns out a lot of the slowdown was caused from running the application under debug mode -- running it normally resulted in acceptable performance.

Related

EditText ,Entered text not visible full

A sample code where i need to have a Edit Text in a Grid Layout Programatically .But when the text are entered in the app ,Only the small bottom portion of text is visible .The text is larger than expected. I need the edit text with text as shown in image which is Edit Text green background with only one line edit text required.Thanks
package com.example.myapplicationtesting;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridLayout;
public class MainActivity extends AppCompatActivity
{
#SuppressLint("ResourceType")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//LinearLayout linearLayout = findViewById(R.id.GroupContainer);
GridLayout Glyout;// = findViewById(R.id.Glayout_item);
Glyout = (GridLayout)findViewById(R.id.id_grid) ;
Glyout.setColumnCount(4);
Glyout.setRowCount(20);
int rowIndex = 0 ;
// Create EditText
for(int i = 0 ; i< 10 ; i++)
{
rowIndex = i ;
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = 50;//ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = 250 ;// GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(0);
param.setMargins(0,5,0,0);
editText.setTextColor(R.color.colorPrimaryDark);
editText.setTextSize(10);
editText.setBackgroundColor(0xFFFFFFFF);
editText.setLayoutParams(param);
if (rowIndex == 1) {
editText.setId( R.id.task1);
}
if (rowIndex == 2) {
editText.setId(R.id.task2);
}
//editText.setHeight(30);
// editText.setWidth(180);
// editText.setBackgroundColor(R.color.colorAccent);
Glyout.addView(editText);
rowIndex++;
}
}
}
enter image description here
try setting param.height = 50; to WRAP_CONTENT
// Create EditText
for(int i = 0 ; i< 10 ; i++)
{
rowIndex = i ;
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = WRAP_CONTENT;
param.width = 250 ;// GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(0);
param.setMargins(0,5,0,0);
editText.setTextColor(R.color.colorPrimaryDark);
editText.setTextSize(10);
editText.setBackgroundColor(0xFFFFFFFF);
editText.setLayoutParams(param);
if (rowIndex == 1) {
editText.setId( R.id.task1);
}
if (rowIndex == 2) {
editText.setId(R.id.task2);
}
//editText.setHeight(30);
// editText.setWidth(180);
// editText.setBackgroundColor(R.color.colorAccent);
Glyout.addView(editText);
rowIndex++;
}

Drag Drawable instead of clicking by its sides to move it

I code a mini game for Android where an animal is controlled by the player when the player clicks on the sides of the Drawable.
I wonder if it is better, and if yes, how to make the Drawable touchable so that the player can drag the character to either side instead of clicking by its sides? I'm interested in both UX/UI opinion and actual solution to the problem.
package dev.android.jamie;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
Log.d("myTag", "This is my message" + parent.getItemAtPosition(pos));
String name = "Jamie";
String str = parent.getItemAtPosition(pos).toString();
if (str.equals("Rookie")) {
cg = new CatchGame(this, 3, name, onScoreListener);
// setContentView(cg);
mainLayout.addView(cg);
getSupportActionBar().hide();
setContentView(mainLayout);
Log.d("game", "Started Rookie game");
} else if (str.equals("Advanced")) {
mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout menuLayout = new LinearLayout(this);
menuLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
textView = new TextView(this);
textView.setVisibility(View.VISIBLE);
str = "Score: 0";
textView.setText(str);
menuLayout.addView(textView);
Button button = new Button(this);
button.setText("Pause");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
togglePausePlay();
}
});
menuLayout.addView(button);
Spinner spinner2 = new Spinner(this);
spinner2.setOnItemSelectedListener(this);
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, spinnerValue);
spinner2.setAdapter(adapter);
menuLayout.addView(spinner2);
mainLayout.addView(menuLayout);
cg = new CatchGame(this, 5, "Jamie", onScoreListener);
cg.setBackground(getResources().getDrawable(R.drawable.bg_land_mdpi));
mainLayout.addView(cg);
// getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getSupportActionBar().hide();
setContentView(mainLayout);
Log.d("game", "Started Advanced game");
} else if (str.equals("Expert")) {
cg = new CatchGame(this, 7, name, onScoreListener);
//setContentView(cg);
mainLayout.addView(cg);
getSupportActionBar().hide();
setContentView(mainLayout);
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
CatchGame cg;
public TextView textView;
public LinearLayout mainLayout;
String[] spinnerValue = {"Difficulty", "Rookie", "Advanced", "Expert", "Master"};
// start app
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout menuLayout = new LinearLayout(this);
menuLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
textView = new TextView(this);
textView.setVisibility(View.VISIBLE);
String str = "Score: 0";
textView.setText(str);
menuLayout.addView(textView);
Button button = new Button(this);
button.setText("Pause");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
togglePausePlay();
}
});
menuLayout.addView(button);
Spinner spinner2 = new Spinner(this);
spinner2.setOnItemSelectedListener(this);
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, spinnerValue);
spinner2.setAdapter(adapter);
menuLayout.addView(spinner2);
mainLayout.addView(menuLayout);
cg = new CatchGame(this, 5, "Jamie", onScoreListener);
cg.setBackground(getResources().getDrawable(R.drawable.bg_land_mdpi));
mainLayout.addView(cg);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getSupportActionBar().hide();
setContentView(mainLayout);
}
private void togglePausePlay() {
if (cg.paused) {
// play
// getSupportActionBar().hide();
Toast.makeText(MainActivity.this, "Play", Toast.LENGTH_SHORT).show();
} else {
// pause
// getSupportActionBar().show();
Toast.makeText(MainActivity.this, "Pause", Toast.LENGTH_SHORT).show();
}
cg.paused = !cg.paused;
}
private OnScoreListener onScoreListener = new OnScoreListener() {
#Override
public void onScore(int score) {
textView.setText("Score: " + score);
}
};
interface OnScoreListener {
void onScore(int score);
}
class CatchGame extends View {
int NBRSTEPS; // number of discrete positions in the x-dimension; must be uneven
String heroName;
int screenW;
int screenH;
int[] x; // x-coordinates for falling objects
int[] y; // y-coordinates for falling objects
int[] hero_positions; // x-coordinates for hero
Random random = new Random();
int ballW; // width of each falling object
int ballH; // height of ditto
float dY; //vertical speed
Bitmap falling, hero, jamie2, jamieleft, jamieright, falling2;
int heroXCoord;
int heroYCoord;
int xsteps;
int score;
int offset;
boolean gameOver; // default value is false
boolean toastDisplayed;
boolean paused = false;
OnScoreListener onScoreListener;
// constructor, load images and get sizes
public CatchGame(Context context, int difficulty, String name, OnScoreListener onScoreListener) {
super(context);
NBRSTEPS = difficulty;
heroName = name;
this.onScoreListener = onScoreListener;
x = new int[NBRSTEPS];
y = new int[NBRSTEPS];
hero_positions = new int[NBRSTEPS];
int resourceIdFalling = 0;
int resourceIdFalling2 = 0;
int resourceIdHero = 0;
if (heroName.equals("Jamie")) {
resourceIdFalling = R.mipmap.falling_object2;
resourceIdFalling2 = R.drawable.coconut_hdpi;
resourceIdHero = R.drawable.left_side_hdpi;
setBackground(getResources().getDrawable(R.mipmap.background));
}
falling = BitmapFactory.decodeResource(getResources(), resourceIdFalling); //load a falling image
falling2 = BitmapFactory.decodeResource(getResources(), resourceIdFalling2); //load a falling image
hero = BitmapFactory.decodeResource(getResources(), resourceIdHero); //load a hero image
jamieleft = BitmapFactory.decodeResource(getResources(), R.drawable.left_side_hdpi); //load a hero image
jamieright = BitmapFactory.decodeResource(getResources(), R.drawable.right_side_hdpi); //load a hero image
ballW = falling.getWidth();
ballH = falling.getHeight();
}
// set coordinates, etc.
void initialize() {
if (!gameOver) { // run only once, when the game is first started
int maxOffset = (NBRSTEPS - 1) / 2;
for (int i = 0; i < x.length; i++) {
int origin = (screenW / 2) + xsteps * (i - maxOffset);
x[i] = origin - (ballW / 2);
hero_positions[i] = origin - hero.getWidth();
}
int heroWidth = hero.getWidth();
int heroHeight = hero.getHeight();
hero = Bitmap.createScaledBitmap(hero, heroWidth * 2, heroHeight * 2, true);
hero = Bitmap.createScaledBitmap(hero, heroWidth * 2, heroHeight * 2, true);
jamieleft = Bitmap.createScaledBitmap(jamieleft, jamieleft.getWidth() * 2, jamieright.getWidth() * 2, true);
jamieright = Bitmap.createScaledBitmap(jamieright, jamieright.getWidth() * 2, jamieright.getWidth() * 2, true);
heroYCoord = screenH - 2 * heroHeight; // bottom of screen
}
for (int i = 0; i < y.length; i++) {
y[i] = -random.nextInt(1000); // place items randomly in vertical direction
}
offset = (NBRSTEPS - 1) / 2; // place hero at centre of the screen
heroXCoord = hero_positions[offset];
// initialize or reset global attributes
dY = 2.0f;
score = 0;
gameOver = false;
toastDisplayed = false;
}
// method called when the screen opens
#Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
screenW = w;
screenH = h;
xsteps = w / NBRSTEPS;
initialize();
}
// method called when the "game over" toast has finished displaying
void restart(Canvas canvas) {
toastDisplayed = true;
initialize();
draw(canvas);
}
// update the canvas in order to display the game action
#Override
public void onDraw(Canvas canvas) {
if (toastDisplayed) {
restart(canvas);
return;
}
super.onDraw(canvas);
int heroHeight = hero.getHeight();
int heroWidth = hero.getWidth();
int heroCentre = heroXCoord + heroWidth / 2;
Context context = this.getContext();
// compute locations of falling objects
for (int i = 0; i < y.length; i++) {
if (!paused) {
y[i] += (int) dY;
}
// if falling object hits bottom of screen
if (y[i] > (screenH - ballH) && !gameOver) {
dY = 0;
gameOver = true;
paused = true;
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
toastDisplayed = true;
}
}, 3000);
//Vibrator v = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
// Vibrate for 3000 milliseconds
//v.vibrate(3000);
}
// if the hero catches a falling object
if (x[i] < heroCentre && x[i] + ballW > heroCentre &&
y[i] > screenH - ballH - heroHeight) {
y[i] = -random.nextInt(1000); // reset to new vertical position
score += 1;
onScoreListener.onScore(score);
}
}
canvas.save(); //Save the position of the canvas.
for (int i = 0; i < y.length; i++) {
if (i % 2 == 0)
canvas.drawBitmap(falling2, x[i], y[i], null); //Draw the falling on the canvas.
else
canvas.drawBitmap(falling, x[i], y[i], null); //Draw the falling on the canvas.
}
canvas.drawBitmap(hero, heroXCoord, heroYCoord, null); //Draw the hero on the canvas.
canvas.restore();
//Call the next frame.
invalidate();
}
// event listener for when the user touches the screen
#Override
public boolean onTouchEvent(MotionEvent event) {
if (paused) {
paused = false;
}
int action = MotionEventCompat.getActionMasked(event);
if (action != MotionEvent.ACTION_DOWN || gameOver) { // non-touchdown event or gameover
return true; // do nothing
}
int coordX = (int) event.getX();
int xCentre = (screenW / 2) - (hero.getWidth() / 2);
int maxOffset = hero_positions.length - 1; // can't move outside right edge of screen
int minOffset = 0; // ditto left edge of screen
if (coordX < xCentre && offset > minOffset) { // touch event left of the centre of screen
offset--; // move hero to the left
if (coordX < heroXCoord)// + heroWidth / 2)
hero = Bitmap.createScaledBitmap(jamieleft, jamieleft.getWidth(), jamieleft.getHeight(), true);
}
if (coordX > xCentre && offset < maxOffset) { // touch event right of the centre of screen
offset++; // move hero to the right
if (coordX > heroXCoord)
hero = Bitmap.createScaledBitmap(jamieright, jamieright.getWidth(), jamieright.getHeight(), true);
}
heroXCoord = hero_positions[offset];
return true;
}
}
}

Adding multiple TextView on runTime android

I'm trying to add multople TextViews to a relativeLayout on runtime.
the reason is that the list is to be created, depending on users choises.
I know how to add 1 textView. but when I entered the code to a loop and tried to creat more than 1, it just doesn't show anything..
pleas help,
int left=70,top=25;
for (String s:startLetterPos){
params.leftMargin = left;
top += 70;
params.topMargin = top;
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText(s);
tv.setVisibility(View.VISIBLE);
tv.setTextSize(20);
testLayout.addView(tv);
}
EDIT: the full code of the activity:
package com.fgdvir.psychowords;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class WordTest extends Activity {
RelativeLayout testLayout;
int displayWidth, displayHeight;
ArrayList<String> startLetterPos = new ArrayList<String>();
//private int[] startLetterPos = new int[26];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.word_test);
startLetterPos = getIntent().getStringArrayListExtra("test");
testLayout = (RelativeLayout) findViewById(R.id.word_test);
create_questions();
// Get Screen size
/*
* Display display = getWindowManager().getDefaultDisplay(); Point size = new ` `Point(); display.getSize(size);
* displayWidth = size.x; displayHeight = size.y;
*/
}
public void create_questions() {
int left=70,top=25;
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT
, LayoutParams.WRAP_CONTENT);
for (String s:startLetterPos){
params.leftMargin = left;
top += 70;
params.topMargin = top;
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText(s);
tv.setVisibility(View.VISIBLE);
tv.setTextSize(20);
testLayout.addView(tv);
}
}
}
so I figured it out,
I still don't know why this doesn't work, but I found another way.
I added the text to a linearLayout, and then the linearLayout to my relative layout:
LinearLayout lL = new LinearLayout(this);
lL.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT
, LayoutParams.WRAP_CONTENT);
for (int i = 0; i<26; i++){
String s = startLetterPos.get(i);
TextView tv = new TextView(this);
tv.setId(i);
tv.setText(s);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
if (i != 0 ){
params.addRule(RelativeLayout.BELOW, i-1);
}
lL.addView(tv,params);
}
testLayout.addView(lL);
}

Adding drawable image to background of canvas

I know its possible to paint the background of canvas using
mPaint = new Paint();
mPaint.setColor(Color.RED);
Im just wondering how to i set a permanent background for it. Ive tried using the xml file but nothing happens. Any ideas?
This is the source code of the project, ive been following a tutorial how to do it because im fairly unfamiliar with bitmaps.
Canvas Class
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class GameBoard extends View{
private int mFlagX = -1;
private int mFlagY = -1;
private Bitmap mBitmap = null;
private Bitmap nBitmap = null;
private Paint mPaint = null;
private boolean isFlagHidden = false;
private int mBoundX = -1;
private int mBoundY = -1;
//play with these values to make the app more or less challenging
public final int CLOSER = 50;
public final int CLOSE = 100;
public GameBoard(Context context, AttributeSet aSet) {
super(context, aSet);
//load our bitmap
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.star);
//create a paint brush
mPaint = new Paint();
mPaint.setColor(Color.RED);
}
#Override
public void onDraw(Canvas canvas) {
//initialize
if ((mFlagX < 1) || (mFlagY < 1)) {
mFlagX = (int) (getWidth() / 2) - mBitmap.getWidth() / 2;
mFlagY = (int) (getHeight() / 2) - mBitmap.getHeight() / 2;
mBoundX = (int)getWidth() - mBitmap.getWidth();
mBoundY = (int)getHeight() - mBitmap.getHeight();
}
//draw background
canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
//draw the flag
if (!isFlagHidden) {
canvas.drawBitmap(mBitmap, mFlagX, mFlagY, null);
}
}
public void hideTheFlag(){
//randomize flag location
mFlagX = (int) Math.ceil(Math.random() * mBoundX);
mFlagY = (int) Math.ceil(Math.random() * mBoundY);
isFlagHidden = true;
//force redraw
invalidate();
}
public void giveUp(){
isFlagHidden = false;
//force redraw
invalidate();
}
public Indicators takeAGuess(float x, float y) {
//this is our "warm" area
Rect prettyClose = new Rect(mFlagX - CLOSE, mFlagY - CLOSE, mFlagX+mBitmap.getWidth() + CLOSE, mFlagY+mBitmap.getHeight() + CLOSE);
//normalize
if (prettyClose.left < 0) prettyClose.left = 0;
if (prettyClose.top < 0) prettyClose.top = 0;
if (prettyClose.right > mBoundX) prettyClose.right = mBoundX;
if (prettyClose.bottom > mBoundY) prettyClose.bottom = mBoundY;
//this is our "hot" area
Rect reallyClose = new Rect(mFlagX - CLOSER, mFlagY - CLOSER, mFlagX+mBitmap.getWidth() + CLOSER, mFlagY+mBitmap.getHeight() + CLOSER);
//normalize
if (reallyClose.left < 0) reallyClose.left = 0;
if (reallyClose.top < 0) reallyClose.top = 0;
if (reallyClose.right > mBoundX) reallyClose.right = mBoundX;
if (reallyClose.bottom > mBoundY) reallyClose.bottom = mBoundY;
//this is the area that contains our flag
Rect bullsEye = new Rect(mFlagX, mFlagY, mFlagX+mBitmap.getWidth(), mFlagY+mBitmap.getHeight());
//check to see where on the board the user pressed
if (bullsEye.contains((int) x, (int)y)) {
//found it
isFlagHidden = false;
invalidate();
return Indicators.BULLSEYE;
} else if (reallyClose.contains((int) x, (int)y)) {
//hot
return Indicators.HOT;
} else if (prettyClose.contains((int)x, (int)y)) {
//warm
return Indicators.WARM;
} else {
//not even close
return Indicators.COLD;
}
}
}
Game Class
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class FindTheStar extends Activity implements OnTouchListener, OnClickListener{
private GameBoard mGameBoard = null;
private boolean isFlagHidden = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_star);
mGameBoard = (GameBoard) findViewById(R.id.Hide_canvas);
mGameBoard.setOnTouchListener(this);
Button b = (Button) findViewById(R.id.the_button);
b.setOnClickListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.Hide_canvas) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (isFlagHidden) {
TextView tv = (TextView)findViewById (R.id.the_label);
switch (mGameBoard.takeAGuess(event.getX(), event.getY())) {
case BULLSEYE:
Button b = (Button) findViewById(R.id.the_button);
isFlagHidden = false;
b.setText("Go Hide!");
tv.setText("You found me!");
tv.setTextColor(Color.GREEN);
break;
case HOT:
tv.setText("You're hot!");
tv.setTextColor(Color.RED);
break;
case WARM:
tv.setText("Getting warm...");
tv.setTextColor(Color.YELLOW);
break;
case COLD:
tv.setText("You're cold.");
tv.setTextColor(Color.BLUE);
break;
}
}
}
return true;
}
return false;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.the_button) {
TextView tv = (TextView)findViewById (R.id.the_label);
tv.setText("");
Button b = (Button) findViewById(R.id.the_button);
isFlagHidden = !isFlagHidden;
if (isFlagHidden) {
b.setText("Can't find me?");
mGameBoard.hideTheFlag();
} else {
b.setText("Go Hide!");
mGameBoard.giveUp();
}
}
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/the_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20sp"
android:layout_marginBottom="10dip"
android:text="Lets Play Hide and Seek!"/>
<Button
android:id="#+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginBottom="10dip"
android:text="Go Hide!"/>
<app.autismapp.GameBoard
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/Hide_canvas"/>
</LinearLayout>
yes you can set your permanent background using xml layout..i done this by creating two class.
this is my code in MainACtivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final BrushView view=new BrushView(this);
setContentView(R.layout.mylayout);//removed this one if the paint doesnt work
view.setBackgroundResource(R.drawable.background);//to set background
setContentView(view);// to display the background
and my second class
public class PaintView extends View {
private Paint paint = new Paint();
public LayoutParams params;
public PaintView(Context context) {
super(context);
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
i hope it gives you an idea

achartengine toScreenPoint(double) always returns nullPointerException

Every time I call this method it return nullpointerexception:
java.lang.NullPointerException at org.achartengine.chart.XYChart.toScreenPoint(XYChart.java:867)
I see mScreenR of chart is null
Without using this method toScreenPoint(double) the charts works well this is the code:
package com.insights.insights.gui;
import java.util.ArrayList;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.chart.XYChart;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import com.insights.insights.R;
import com.insights.insights.local.ApplicationsController;
import com.insights.insights.model.AppMetrics;
import com.insights.insights.model.Application;
import com.insights.insights.model.Applications;
import com.insights.insights.model.Day;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
public class ChartFragment extends Fragment {
private XYMultipleSeriesRenderer renderer;
private XYMultipleSeriesDataset dataset;
private GraphicalView graphicalView;
private XYSeries firstSeries;
private XYChart chart=null;
private String apiKey;
private ArrayList<Day> days;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiKey = getArguments().getString(getString(R.string.tabs_activity_api_key));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.chart_fragment, container, false);
v.findViewById(R.idChartFragment.container).requestFocus();
this.view = v;
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Obtaining data to plot
Applications applications = ApplicationsController.getInstance(getActivity()).getApplications();
ArrayList<Application> applicationArray = applications.getApplication();
if (applicationArray != null && !applicationArray.isEmpty()) {
for (int i = 0; i < applicationArray.size(); i++) {
if (applicationArray.get(i).getApiKey().equals(apiKey)) {
ArrayList<AppMetrics> appMetrics = applicationArray.get(i).getAppMetrics();
for (int j = 0; j < appMetrics.size(); j++) {
if (appMetrics.get(j).getMetric().equals("Sessions")) {
days = appMetrics.get(j).getDay();
break;
}
}
}
}
}
// If there isn't any item to plot and show a toast
if (days == null) {
Toast toast = Toast.makeText(getActivity(), R.string.chart_fragment_no_items, Toast.LENGTH_LONG);
toast.show();
return;
}
// Ploting the items
dataset = getDataset(days);
renderer = getRenderer();
setRendererStyling(renderer);
// add plot to the layout
if (graphicalView == null) {
LinearLayout layout = (LinearLayout) view.findViewById(R.idChartFragment.Chart);
chart= new LineChart(dataset, renderer);
graphicalView = new GraphicalView(getActivity(), chart);
renderer.setSelectableBuffer(11);
layout.addView(graphicalView);
} else{
graphicalView.repaint();
}
if(chart!=null&&firstSeries!=null){
for(int i=0;i<firstSeries.getItemCount();i++){
double x = firstSeries.getX(i);
double y = firstSeries.getY(i);
double[] screenPoint = chart.toScreenPoint(new double[] { x, y },0);
Log.i("puntos", x + "," + y + " = "+" ("+screenPoint[0]+", "+screenPoint[1]+")");
}
}
}
/**
* Method for set the style of the plotter window and the string at the x
* axis
*
* #param mRenderer
* render to put style in
*
* #param dataSetX
* string to set at x axis
*/
private void setRendererStyling(XYMultipleSeriesRenderer mRenderer) {
mRenderer.setApplyBackgroundColor(false);
mRenderer.setMarginsColor(R.drawable.transperent_color);
mRenderer.setMargins(new int[] { 0, 0, 0, 0 });
mRenderer.setShowAxes(false);
mRenderer.setZoomButtonsVisible(false);
mRenderer.setExternalZoomEnabled(false);
mRenderer.setPointSize(20);
mRenderer.setClickEnabled(false);
mRenderer.setDisplayValues(false);
mRenderer.setXLabels(0);
mRenderer.setYLabels(0);
mRenderer.setPanEnabled(false);
mRenderer.setZoomEnabled(false);
mRenderer.setShowLegend(false);
}
/**
* Method to introduce the values of the y axis
*
* #param dataSetY
* data to set at axis y
* #return the data to set
*/
private XYMultipleSeriesDataset getDataset(ArrayList<Day> days) {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
firstSeries = new XYSeries("");
for (int i = 0; i < 12; i++) {
int value = Integer.parseInt(days.get(days.size() - (13 - i)).getValue());
firstSeries.add(i, value);
}
dataset.addSeries(firstSeries);
return dataset;
}
/**
* Method for set the style of the line you want to plot and create a new
* renderer
*
* #return the renderer
*/
private XYMultipleSeriesRenderer getRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(getResources().getColor(R.color.grey_number_label_background));
r.setLineWidth(getResources().getInteger(R.integer.chart_fragment_line_width));
// r.setDisplayChartValues(true);
r.setPointStyle(PointStyle.POINT);
r.setFillPoints(true);
renderer.addSeriesRenderer(r);
return renderer;
}
}
And this is the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+idChartFragment/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<LinearLayout
android:id="#+idChartFragment/Chart"
android:layout_width="300dp"
android:layout_height="300dp"
android:orientation="horizontal"/>
<AbsoluteLayout
android:id="#+idChartFragment/absolute"
android:layout_width="300dp"
android:layout_height="300dp"/>
</RelativeLayout>
Second Edit:
I want to do something like this:
With my code I do this:
This is my code:
package com.insights.insights.gui;
import java.util.ArrayList;
import java.util.List;
import org.achartengine.GraphicalView;
import org.achartengine.chart.ClickableArea;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.chart.XYChart;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Layout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.ItemizedOverlay.OnFocusChangeListener;
import com.insights.insights.R;
import com.insights.insights.local.ApplicationsController;
import com.insights.insights.model.AppMetrics;
import com.insights.insights.model.Application;
import com.insights.insights.model.Applications;
import com.insights.insights.model.Day;
/**
*
* #author Manuel Plazas Palacio
*
*/
public class ChartFragment extends Fragment {
private XYMultipleSeriesRenderer renderer;
private XYMultipleSeriesDataset dataset;
private GraphicalView graphicalView;
private XYSeries firstSeries;
private XYChart chart = null;
private AbsoluteLayout absoluteLayout;
private ImageView point;
private LinearLayout pointInfoConatiner;
private TextView pointNumberText;
private TextView pointNameText;
private TextView pointDateText;
private Typeface avenirHeavy;
private Typeface avenirLight;
private String apiKey;
private String metricName;
private ArrayList<Day> days;
// The max and the min values displayed
private double max = 0;
private double min = 0;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiKey = getArguments().getString(getString(R.string.tabs_activity_api_key));
metricName = "Sessions";
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.chart_fragment, container, false);
v.findViewById(R.idChartFragment.container).requestFocus();
this.view = v;
absoluteLayout = (AbsoluteLayout) v.findViewById(R.idChartFragment.absolute);
// pointInfoConatiner = (LinearLayout) v.findViewById(R.idChartFragment.pointInfoContainer);
// pointNumberText = (TextView) v.findViewById(R.idChartFragment.pointNumberText);
// pointNameText = (TextView) v.findViewById(R.idChartFragment.pointNameText);
// pointDateText = (TextView) v.findViewById(R.idChartFragment.pointDateText);
//
// pointNameText.setText(metricName);
// Obtaining data to plot
Applications applications = ApplicationsController.getInstance(getActivity()).getApplications();
ArrayList<Application> applicationArray = applications.getApplication();
if (applicationArray != null && !applicationArray.isEmpty()) {
for (int i = 0; i < applicationArray.size(); i++) {
if (applicationArray.get(i).getApiKey().equals(apiKey)) {
ArrayList<AppMetrics> appMetrics = applicationArray.get(i).getAppMetrics();
for (int j = 0; j < appMetrics.size(); j++) {
if (appMetrics.get(j).getMetric().equals(metricName)) {
days = appMetrics.get(j).getDay();
break;
}
}
}
}
}
// If there isn't any item to plot and show a toast
if (days == null) {
Toast toast = Toast.makeText(getActivity(), R.string.chart_fragment_no_items, Toast.LENGTH_LONG);
toast.show();
}
// Ploting the items
dataset = getDataset(days);
renderer = getRenderer();
setRendererStyling(renderer);
// add plot to the layout
if (graphicalView == null) {
LinearLayout layout = (LinearLayout) view.findViewById(R.idChartFragment.Chart);
chart = new LineChart(dataset, renderer);
graphicalView = new GraphicalView(getActivity(), chart);
renderer.setSelectableBuffer(11);
layout.addView(graphicalView);
} else {
graphicalView.repaint();
}
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
avenirHeavy = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Avenir Heavy.ttf");
avenirLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Avenir Light.ttf");
graphicalView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = graphicalView.getCurrentSeriesAndPoint();
double[] xy = graphicalView.toRealPoint(0);
//creating the views
createOnClickPointsView();
if (seriesSelection != null) {
// debug
Log.d("Punto", seriesSelection.getXValue() + ", " + seriesSelection.getValue());
double x = firstSeries.getX(seriesSelection.getPointIndex() + 1);
double y = firstSeries.getY(seriesSelection.getPointIndex() + 1);
double[] screenPoint = chart.toScreenPoint(new double[] { x, y });
// debug
Log.d("Chart point", "Chart element in series index " + seriesSelection.getSeriesIndex() + " data point index "
+ seriesSelection.getPointIndex() + " was clicked" + " closest point value X=" + seriesSelection.getXValue()
+ ", Y=" + seriesSelection.getValue() + " clicked point value X=" + (float) xy[0] + ", Y=" + (float) xy[1]);
Log.d("Punto pantalla", " (" + screenPoint[0] + ", " + screenPoint[1] + ")");
int value = Integer.parseInt(days.get((int) (days.size() - (13 - x))).getValue());
String date = days.get((int) (days.size() - (13 - x))).getDate();
pointNumberText.setText(value + "");
pointDateText.setText(date);
// drawing point info
absoluteLayout.addView(pointInfoConatiner, new LayoutParams(getResources().getDrawable(R.drawable.graficapin)
.getIntrinsicWidth(), getResources().getDrawable(R.drawable.graficapin).getIntrinsicHeight(),
(int) (screenPoint[0] - (getResources().getDrawable(R.drawable.graficapin).getIntrinsicWidth() / 2)),
(int) (screenPoint[1] - (getResources().getDrawable(R.drawable.graficapin).getIntrinsicHeight()))));
// drawing point clicked
absoluteLayout.addView(point, new LayoutParams(getResources().getDrawable(R.drawable.puntoon).getIntrinsicWidth(),
getResources().getDrawable(R.drawable.puntoon).getIntrinsicHeight(), (int) (screenPoint[0] - (getResources()
.getDrawable(R.drawable.puntoon).getIntrinsicWidth() / 2)), (int) (screenPoint[1] - ((getResources()
.getDrawable(R.drawable.puntoon).getIntrinsicHeight()) / 4))));
}
}
});
}
/**
* Method for set the style of the plotter window and the string at the x
* axis
*
* #param mRenderer
* render to put style in
*
* #param dataSetX
* string to set at x axis
*/
private void setRendererStyling(XYMultipleSeriesRenderer mRenderer) {
mRenderer.setApplyBackgroundColor(false);
mRenderer.setMarginsColor(R.drawable.transperent_color);
mRenderer.setMargins(new int[] { 0, 0, 0, 0 });
mRenderer.setShowAxes(false);
mRenderer.setZoomButtonsVisible(false);
mRenderer.setExternalZoomEnabled(false);
mRenderer.setPointSize(getResources().getInteger(R.integer.chart_fragment_point_size));
mRenderer.setClickEnabled(true);
mRenderer.setDisplayValues(false);
mRenderer.setXLabels(0);
mRenderer.setYLabels(0);
mRenderer.setPanEnabled(true);
mRenderer.setZoomEnabled(false);
mRenderer.setShowLegend(false);
mRenderer.setYAxisMax(max + 10);
mRenderer.setYAxisMin(min - 10);
}
/**
* Method to introduce the values of the y axis
*
* #param dataSetY
* data to set at axis y
* #return the data to set
*/
private XYMultipleSeriesDataset getDataset(ArrayList<Day> days) {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
firstSeries = new XYSeries("");
for (int i = 0; i < 12; i++) {
int value = Integer.parseInt(days.get(days.size() - (13 - i)).getValue());
firstSeries.add(i, value);
}
dataset.addSeries(firstSeries);
XYSeries secondSeries = new XYSeries("");
for (int i = 1; i < 11; i++) {
int value = Integer.parseInt(days.get(days.size() - (13 - i)).getValue());
if (i == 1) {
max = value;
min = value;
}
if (value > max)
max = value;
if (value < min)
min = value;
secondSeries.add(i, value);
}
dataset.addSeries(secondSeries);
return dataset;
}
/**
* Method for set the style of the line you want to plot and create a new
* renderer
*
* #return the renderer
*/
private XYMultipleSeriesRenderer getRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
//First chart with the line
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(getResources().getColor(R.color.grey_number_label_background));
r.setLineWidth(getResources().getInteger(R.integer.chart_fragment_line_width));
// r.setDisplayChartValues(true);
r.setPointStyle(PointStyle.POINT);
r.setFillPoints(true);
renderer.addSeriesRenderer(r);
// Second chart with the points
XYSeriesRenderer r1 = new XYSeriesRenderer();
r1.setColor(getResources().getColor(R.color.purple_chart_points));
r1.setLineWidth(0);
r1.setFillPoints(true);
r1.setPointStyle(PointStyle.CIRCLE);
renderer.addSeriesRenderer(r1);
return renderer;
}
public XYSeries getFirstSeries() {
return firstSeries;
}
public void setFirstSeries(XYSeries firstSeries) {
this.firstSeries = firstSeries;
}
public XYChart getChart() {
return chart;
}
public void setChart(XYChart chart) {
this.chart = chart;
}
/**
* Method for create the views when clicking on a point of the chart
*/
private void createOnClickPointsView() {
//If the info is already visible
if (pointInfoConatiner != null)
absoluteLayout.removeView(pointInfoConatiner);
// If the point is drawn
if (point != null)
absoluteLayout.removeView(point);
pointInfoConatiner = new LinearLayout(getActivity());
pointInfoConatiner.setBackgroundDrawable(getResources().getDrawable(R.drawable.graficapin));
pointInfoConatiner.setOrientation(LinearLayout.VERTICAL);
pointInfoConatiner.setGravity(Gravity.CENTER_HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 8, 0, 0);
pointNumberText = new TextView(getActivity());
pointNumberText.setTextSize(18);
pointNumberText.setTextColor(getResources().getColor(R.color.purple_chart_points));
pointNumberText.setTypeface(avenirHeavy);
pointNumberText.setGravity(Gravity.CENTER);
pointNameText = new TextView(getActivity());
pointNameText.setTextSize(18);
pointNameText.setTextColor(getResources().getColor(R.color.grey_users_label));
pointNameText.setTypeface(avenirLight);
pointNameText.setText(metricName);
pointNameText.setGravity(Gravity.CENTER);
pointDateText = new TextView(getActivity());
pointDateText.setTextSize(11);
pointDateText.setTextColor(getResources().getColor(R.color.grey_users_label));
pointDateText.setTypeface(avenirHeavy);
pointDateText.setGravity(Gravity.CENTER);
pointInfoConatiner.addView(pointNumberText, 0, layoutParams);
layoutParams.setMargins(0, 2, 0, 0);
pointInfoConatiner.addView(pointNameText, 1, layoutParams);
pointInfoConatiner.addView(pointDateText, 2, layoutParams);
point = new ImageView(getActivity());
point.setImageDrawable(getResources().getDrawable(R.drawable.puntoon));
}
}
Anyone know how can I:
1-Quit the bottom border
2-Quit the line of the pink chart
3-The chart don't move when I touch the points
4- When I ask for the screen point why to many times the y value returns infinite
There used to be this bug in an older version of AChartEngine. I suggest you update to 1.1.0.
Also, please note that the chart must have been already displayed when calling the method. If the chart didn't display on screen then there is no way to calculate that.

Categories

Resources