I'm trying to create something like this. The problem is how to create vertical lines close to the seekbar. I tried the code given here, but the seekbar line disappears. Any help would be appreciated. Here is what I've done so far.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBar sb = (SeekBar)findViewById(R.id.seekBar1);
//Get the width of the main view.
Display display = getWindowManager().getDefaultDisplay();
Point displaysize = new Point();
display.getSize(displaysize);
int width = displaysize.x;
//set the seekbar maximum (Must be a even number, having a remainder will cause undersirable results)
//this variable will also determine the number of points on the scale.
int seekbarmax = 10;
int seekbarpoints = (width/seekbarmax); //this will determine how many points on the scale there should be on the seekbar
//find the seekbar in the view, and set some behaviour properties
SeekBar seekbar = (SeekBar)findViewById(R.id.seekBar1);
//Set the seekbar to a max range of 10
seekbar.setMax(seekbarmax);
//Create a new bitmap that is the width of the screen
Bitmap bitmap = Bitmap.createBitmap(width, 100, Bitmap.Config.ARGB_8888);
//A new canvas to draw on.
Canvas canvas = new Canvas(bitmap);
//a new style of painting - colour and stoke thickness.
Paint paint = new Paint();
paint.setColor(Color.BLUE); //Set the colour to red
paint.setStyle(Paint.Style.STROKE); //set the style
paint.setStrokeWidth(1); //Stoke width
Paint textpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textpaint.setColor(Color.rgb(61, 61, 61));// text color RGB
textpaint.setTextSize(28);// text size
int point = 0; //initiate the point variable
//Start a for loop that will loop seekbarpoints number of times.
for (int i = 0; i < seekbarpoints; i++ ){
if ((i%2)==0) {
//short line
point = point + seekbarpoints;
canvas.drawLine(point, 30, point, 0, paint);
//drawLine(startx,startx,endy,endy)
}
//Create a new Drawable
Drawable d = new BitmapDrawable(getResources(),bitmap);
//Set the seekbar widgets background to the above drawable.
seekbar.setProgressDrawable(d);
}
}
}
I was searching for the this for long time and only got an answer to draw the numbers. Thus I decided to do it myself. I took the solution having only the steps and extended it by adding the logic for the intervals.
Please see the below image.
I then successfully created a seekbar with interval lables and vertical lines over seekbar. The above image is what I've achieved.
However there are few optimization in the padding which you can work on adjusting the dimensions.
Solution :
The xml file for the intervals:
seekbar_with_intervals_labels
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textViewInterval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#707070"/>
XML for the Vertical deviders : seekbar_vertical_lines
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textViewVerticalLine"
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#drawable/lines" />
Then the custom Seekbar class :
package com.example.abc.myapplication;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import com.example.abc.myapplication.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SeekbarWithIntervals extends LinearLayout {
private RelativeLayout RelativeLayout = null;
private SeekBar Seekbar = null;
private RelativeLayout Divider = null;
private View verticalLine = null;
private int WidthMeasureSpec = 0;
private int HeightMeasureSpec = 0;
public SeekbarWithIntervals(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
getActivity().getLayoutInflater()
.inflate(R.layout.seekbar_with_intervals, this);
}
private Activity getActivity() {
return (Activity) getContext();
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
verticalLine = new View(getActivity());
verticalLine.setLayoutParams(new LayoutParams(2, LayoutParams.MATCH_PARENT));
verticalLine.setBackgroundColor(Color.BLACK);
if (changed) {
alignIntervals();
// We've changed the intervals layout, we need to refresh.
RelativeLayout.measure(WidthMeasureSpec, HeightMeasureSpec);
RelativeLayout.layout(RelativeLayout.getLeft(), RelativeLayout.getTop(), RelativeLayout.getRight(), RelativeLayout.getBottom());
}
}
private void alignIntervals() {
int widthOfSeekbarThumb = getSeekbarThumbWidth();
int thumbOffset = widthOfSeekbarThumb / 2;
int widthOfSeekbar = getSeekbar().getWidth();
int firstIntervalWidth = getRelativeLayout().getChildAt(0).getWidth();
int remainingPaddableWidth = widthOfSeekbar - firstIntervalWidth - widthOfSeekbarThumb;
int numberOfIntervals = getSeekbar().getMax();
int maximumWidthOfEachInterval = remainingPaddableWidth / numberOfIntervals;
alignFirstInterval(thumbOffset);
alignIntervalsInBetween(maximumWidthOfEachInterval);
alignLastInterval(thumbOffset, maximumWidthOfEachInterval);
}
private int getSeekbarThumbWidth() {
return getResources().getDimensionPixelOffset(R.dimen.seekbar_thumb_width);
}
private void alignFirstInterval(int offset) {
TextView firstInterval = (TextView) getRelativeLayout().getChildAt(0);
firstInterval.setPadding(offset - 10, 0, 0, 0);
TextView firstLine = (TextView) getDivider().getChildAt(0);
firstLine.setPadding(offset + 10, 0, 0, 0);
}
private void alignIntervalsInBetween(int maximumWidthOfEachInterval) {
int widthOfPreviousIntervalsText = 0;
int widthOfPreviousLine = 0;
// Don't align the first or last interval.
for (int index = 1; index < (getRelativeLayout().getChildCount() - 1); index++) {
TextView textViewInterval = (TextView) getRelativeLayout().getChildAt(index);
int widthOfText = textViewInterval.getWidth();
// This works out how much left padding is needed to center the current interval.
//int leftPadding = Math.round(maximumWidthOfEachInterval - (widthOfText / 2) - (widthOfPreviousIntervalsText / 2) - (widthOfText / 2));
int leftPadding = Math.round(maximumWidthOfEachInterval - (widthOfText / 2) - (widthOfPreviousIntervalsText / 2) - (widthOfText / index ) + index + 5 * 5);
textViewInterval.setPadding(leftPadding, 0, 0, 0);
widthOfPreviousIntervalsText = widthOfText;
TextView textViewLine = (TextView) getDivider().getChildAt(index);
int widthOfLine = textViewLine.getWidth();
// This works out how much left padding is needed to center the current interval.
leftPadding = (maximumWidthOfEachInterval + (index + (maximumWidthOfEachInterval / 10)) - (index * 4)); //Math.round(maximumWidthOfEachInterval + (widthOfLine ) + (widthOfPreviousLine ));
//leftPadding = Math.round((maximumWidthOfEachInterval - (widthOfPreviousLine / index) - (widthOfPreviousLine / index) - (widthOfPreviousLine / index)) + 10);
textViewLine.setPadding(leftPadding , 0, 0, 0);
widthOfPreviousLine = widthOfLine;
}
}
private void alignLastInterval(int offset, int maximumWidthOfEachInterval) {
int lastIndex = getRelativeLayout().getChildCount() - 1;
TextView lastInterval = (TextView) getRelativeLayout().getChildAt(lastIndex);
int widthOfText = lastInterval.getWidth();
int leftPadding = Math.round(maximumWidthOfEachInterval - widthOfText - offset);
lastInterval.setPadding(leftPadding + 20, 0, 0, 0);
TextView lastLine = (TextView) getDivider().getChildAt(lastIndex);
leftPadding = Math.round(maximumWidthOfEachInterval - (widthOfText / 5) - (widthOfText / 5) - (widthOfText / 5 ) + 3 * 10);
lastLine.setPadding(leftPadding , 0, 0, 0);
}
protected synchronized void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
WidthMeasureSpec = widthMeasureSpec;
HeightMeasureSpec = heightMeasureSpec;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int getProgress() {
return getSeekbar().getProgress();
}
public void setProgress(int progress) {
getSeekbar().setProgress(progress);
}
public void setIntervals(List<String> intervals) {
displayIntervals(intervals);
getSeekbar().setMax(intervals.size() - 1);
}
private void displayIntervals(List<String> intervals) {
int idOfPreviousInterval = 0;
int idOfPreviousLine = 0;
if (getRelativeLayout().getChildCount() == 0) {
for (String interval : intervals) {
TextView textViewInterval = createInterval(interval);
alignTextViewToRightOfPreviousInterval(textViewInterval, idOfPreviousInterval);
TextView textViewVerticaLine = createVerticalLine();
alignTextViewToRightOfPreviousInterval(textViewVerticaLine, idOfPreviousLine);
idOfPreviousLine = textViewVerticaLine.getId();
idOfPreviousInterval = textViewInterval.getId();
getRelativeLayout().addView(textViewInterval);
getDivider().addView(textViewVerticaLine);
}
}
}
private TextView createInterval(String interval) {
View textBoxView = (View) LayoutInflater.from(getContext())
.inflate(R.layout.seekbar_with_intervals_labels, null);
TextView textView = (TextView) textBoxView
.findViewById(R.id.textViewInterval);
textView.setId(View.generateViewId());
textView.setText(interval);
return textView;
}
private TextView createVerticalLine() {
View textBoxView = (View) LayoutInflater.from(getContext())
.inflate(R.layout.seekbar_vertical_lines, null);
TextView textView = (TextView) textBoxView
.findViewById(R.id.textViewVerticalLine);
textView.setId(View.generateViewId());
return textView;
}
private void alignTextViewToRightOfPreviousInterval(TextView textView, int idOfPreviousInterval) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (idOfPreviousInterval > 0) {
params.addRule(RelativeLayout.RIGHT_OF, idOfPreviousInterval);
}
textView.setLayoutParams(params);
}
public void setOnSeekBarChangeListener(OnSeekBarChangeListener onSeekBarChangeListener) {
getSeekbar().setOnSeekBarChangeListener(onSeekBarChangeListener);
}
private RelativeLayout getRelativeLayout() {
if (RelativeLayout == null) {
RelativeLayout = (RelativeLayout) findViewById(R.id.intervals);
}
return RelativeLayout;
}
private SeekBar getSeekbar() {
if (Seekbar == null) {
Seekbar = (SeekBar) findViewById(R.id.seekbar);
}
return Seekbar;
}
private RelativeLayout getDivider() {
if (Divider == null) {
Divider = (RelativeLayout) findViewById(R.id.fl_divider);
}
return Divider;
}
}
Then the MainActivity where we dynamically add the intervals.
public class MainActivity extends AppCompatActivity {
private SeekbarWithIntervals SeekbarWithIntervals = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> seekbarIntervals = getIntervals();
getSeekbarWithIntervals().setIntervals(seekbarIntervals);
}
private List<String> getIntervals() {
return new ArrayList<String>() {{
add("45");
add("55");
add("65");
add("75");
add("85");
add("95");
}};
}
private SeekbarWithIntervals getSeekbarWithIntervals() {
if (SeekbarWithIntervals == null) {
SeekbarWithIntervals = (SeekbarWithIntervals) findViewById(R.id.seekbarWithIntervals);
}
return SeekbarWithIntervals;
}
}
You can put the padding bottom of the divider so as to push it upwards like in your image.
Note : You can also have a single layout defining the divider and the number layout.
You will need two PNG drawables one for background and one for progress.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#android:id/background"
android:drawable="#drawable/seekbar_drawable_frost" />
<item
android:id="#android:id/progress"
android:drawable="#drawable/seekbar_drawable_frost_progress" />
</layer-list>
Related
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;
}
}
}
I want to show 3x3 sized gridview. I want to set the height and width based on device size. I am taking reference from this link.
MainActivity-
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main-
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Edit-
Like first getting screen height and width then each item height and width 1/3 of the value of screen height and width I am getting.
Do not use screen size, in a multi-windows context this method is invalid.
If your grid is a 3x3 items size fixed, so use custom layout ViewGroup like this: (and set RelativeLayout items content)
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle state) {
setContentView(new ViewGroup(this) {
private RelativeLayout[] items = new RelativeLayout[9];
private int width, height, itemWidth, itemHeight;
{
Random r = new Random();
for (int i = 0; i < 9; i++) {
items[i] = new RelativeLayout(getContext());
float[] hsv = new float[] {360 * r.nextFloat(), .50f, .75f};
items[i].setBackgroundColor(Color.HSVToColor(hsv));
addView(items[i]);
// UPDATE ////////////////////////////////////
ImageView image = new ImageView(getContext());
switch (i) {
case 0: // top left
case 1: // top center
case 2: // top right
case 3: // center left
case 4: // center center
case 5: // center right
case 6: // bottom left
case 7: // bottom center
case 8: // bottom right
image.setImageResource(R.drawable.ic_launcher);
break;
}
image.setScaleType(ScaleType.FIT_XY);
image.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
));
items[i].addView(image);
//////////////////////////////////////////////
}
}
#Override
protected void onMeasure(int wMS, int hMS) {
width = MeasureSpec.getSize(wMS);
height = MeasureSpec.getSize(hMS);
itemWidth = width / 3;
itemHeight = height / 3;
wMS = MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY);
hMS = MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY);
measureChildren(wMS, hMS);
setMeasuredDimension(width, height);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < 9; i++) {
l = itemWidth * (i % 3);
t = itemHeight * (i / 3);
r = l + itemWidth;
b = t + itemHeight;
items[i].layout(l, t, r, b);
}
}
});
super.onCreate(state);
}
}
EDIT : see my update in code, you have simply to add your images to the items containers. With this method, no XML layout file needed because you manage content and size yourself.
Result :
EDIT : the minimalist way:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle state) {
setContentView(new ViewGroup(this) {
private static final int SIZE_X = 3;
private static final int SIZE_Y = 3;
private ImageView[] items = new ImageView[SIZE_X * SIZE_Y];
private int itemWidth, itemHeight;
{
setBackgroundColor(Color.DKGRAY);
for (int i = 0; i < items.length; i++) {
items[i] = new ImageView(getContext());
items[i].setScaleType(ScaleType.CENTER);
items[i].setImageResource(R.drawable.ic_launcher);
addView(items[i]);
}
}
#Override
protected void onMeasure(int wMS, int hMS) {
int width = MeasureSpec.getSize(wMS);
int height = MeasureSpec.getSize(hMS);
itemWidth = width / SIZE_X;
itemHeight = height / SIZE_Y;
wMS = MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY);
hMS = MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY);
measureChildren(wMS, hMS);
setMeasuredDimension(width, height);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < items.length; i++) {
l = itemWidth * (i % SIZE_X);
t = itemHeight * (i / SIZE_X);
r = l + itemWidth;
b = t + itemHeight;
items[i].layout(l, t, r, b);
}
}
});
super.onCreate(state);
}
}
Result :
# Kanwaljit Singh:
In MainActivity items creation loop:
final int id = i;
items[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getContext(), NextActivity.class).putExtra("id", id));
}
});
In NextActivity:
int id = getIntent().getIntExtra("id", -1);
You can get the screen dimensions like:
final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp=displayMetrics.widthPixels;
Log.WTF("ScreenWidth", "width: "+screenWidthInDp+", menuWidth: "+screenWidthInDp/3);
And for the gridview, I would suggest you to take a look at this awesome library called Staggered Grid View. And their sample here.
I use the following approach when I have to resize my Activitys, I assume the same is valid for your case:
// I'm storing the size of the window in the display var, so I can then play around
final Display display = getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
// In your case, you'll probably need something like this:
GridView gv = (GridView) findViewById(R.id.gridview);
gv.setWidth((int) size.x * 0.75); // Whis would resize the grid width to the 75%
gv.setHeight((int) size.y * 0.5); // Same with the height, but to the 50%
Hi I am creating a custom view in android.I have a LinerarLayout to which I am adding the custom views.I manage to add one custom view programmatically but if I add another it's not getting added into the layout.I don't know where am going wrong.My Main activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout container = (LinearLayout) findViewById(R.id.container);
final MyAnimationView animView = new MyAnimationView(this);
container.addView(animView);
final MyAnimationView animView1 = new MyAnimationView(this);
container.addView(animView1);
}
and my custom view class
public class MyAnimationView extends TextView implements ValueAnimator.AnimatorUpdateListener {
public final ArrayList<ShapeHolder> balls = new ArrayList<ShapeHolder>();
AnimatorSet animation = null;
private float mDensity;
public MyAnimationView(Context context) {
super(context);
mDensity = getContext().getResources().getDisplayMetrics().density;
ShapeHolder ball0 = addBall(75f, 400f);
}
public MyAnimationView(Context context,float x,float y) {
super(context);
mDensity = getContext().getResources().getDisplayMetrics().density;
ShapeHolder ball0 = addBall(105f, 400f);
}
private void createAnimation() {
if (animation == null) {
ObjectAnimator anim0=ObjectAnimator.ofFloat(balls.get(0),"y",getHeight(),500f).setDuration(500);
animation = new AnimatorSet();
animation.playTogether(anim0);
anim0.addUpdateListener(this);
}
}
private ShapeHolder addBall(float x, float y) {
OvalShape circle = new OvalShape();
circle.resize(100f * mDensity, 100f * mDensity);
ShapeDrawable drawable = new ShapeDrawable(circle);
ShapeHolder shapeHolder = new ShapeHolder(drawable);
shapeHolder.setX(x - 25f);
shapeHolder.setY(y - 25f);
int red = (int)(100 + Math.random() * 155);
int green = (int)(100 + Math.random() * 155);
int blue = (int)(100 + Math.random() * 155);
int color = 0xff000000 | red << 16 | green << 8 | blue;
Paint paint = drawable.getPaint(); //new Paint(Paint.ANTI_ALIAS_FLAG);
int darkColor = 0xff000000 | red/4 << 16 | green/4 << 8 | blue/4;
RadialGradient gradient = new RadialGradient(37.5f, 12.5f,
50f, color, darkColor, Shader.TileMode.CLAMP);
paint.setShader(gradient);
shapeHolder.setPaint(paint);
balls.add(shapeHolder);
return shapeHolder;
}
#Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < balls.size(); ++i) {
ShapeHolder shapeHolder = balls.get(i);
canvas.save();
canvas.translate(shapeHolder.getX(), shapeHolder.getY());
shapeHolder.getShape().draw(canvas);
canvas.restore();
}
}
public void startAnimation() {
createAnimation();
animation.start();
}
public void onAnimationUpdate(ValueAnimator animation) {
invalidate();
}
}
EDIT:here is my linear layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
any help will be greatly appreciated.
Just an assumption, donĀ“t know if it works. Try to do this in Your main:
LinearLayout container = (LinearLayout) findViewById(R.id.container);
final MyAnimationView animView = new MyAnimationView(this);
animView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.
WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
container.addView(animView);
final MyAnimationView animView1 = new MyAnimationView(this);
animView1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.
WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
container.addView(animView1);
does it work?
No it will be added but you can't see it. because your first view will take the full space of your screen. And your second will be added in below of your first view so it will be hidden from visible part of your device. I also met the same problem. I solved this with two layouts. see here for my solution.
I assume this is the problem that is why I provided this solution if not kindly let me know..
I am using a View extended from View group and the onDraw is not getting called when I call invalidate.Can any one please explain?
The code is given below
public class BarGraph extends View {
private int viewHeight;
private int viewWidth; // height and width of bar graph dynamically calculated.
private int mGraphColor; // the colour of the bar graph.
private ArrayList<Integer> mTodays; // The array list that handles the input to draw the graph.
private final int barCount = 20; // Number of bars in the bar graph...here set as 20.
/*
* The maximum action value a bar can take.
* This is calculated based on the action array
* passed to the chart.
*/
private int yMax = 0;
private Paint graphColor;
public BarGraph(Context context, int graphColor) {
super(context);
this.setWillNotDraw(false);
mGraphColor = graphColor;
setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
initializePaintObjects();
}
public BarGraph(Context context, AttributeSet attrs) {
super(context, attrs);
this.setWillNotDraw(false);
initializePaintObjects();
}
private void initializePaintObjects(){
graphColor = new Paint();
graphColor.setColor(mGraphColor);
graphColor.setStyle(Style.FILL);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(mTodays == null) // If the array list is empty.
return;
if(yMax <= 0)
return;
int left = 0;
viewHeight = getHeight();
viewWidth = getWidth();
if((viewWidth % barCount) > 0){ //adjusting the view width so that bars correctly fits in
int newWidth = (int) (Math.floor(viewWidth / barCount) * barCount);
left = (int) Math.floor(((viewWidth - newWidth)/2));
viewWidth = (int) Math.floor((viewWidth / barCount) * barCount);
}
int columnWidth = 2;
columnWidth = (int) Math.floor(viewWidth / barCount);
int xFactor = 1;
xFactor = (int) Math.ceil(columnWidth * 0.33);
int barWidth = 1;
barWidth = columnWidth - xFactor;
graphColor.setStrokeWidth(barWidth);
int j = 0;
for(int i = 0; i < mTodays.size() ; i++){
int todayValue = mTodays.get(i);
float todaysHeight;
if(todayValue == 0){
todaysHeight = (float) (viewHeight-viewHeight*(.001));
}else{
todaysHeight = getYValue(todayValue);
}
canvas.drawLine(((j*columnWidth)+xFactor + left) , viewHeight, ((j*columnWidth)+xFactor + left), todaysHeight, graphColor);
j++;
}
}
public void setData(ArrayList<Integer>todays){
mTodays = todays;
yMax = 0;
for (int val : mTodays){
yMax = yMax > val ? yMax : val;
}
invalidate();
}
private int getYValue(int item){
int percent = (item * 100)/yMax;
return (viewHeight) - ((percent * viewHeight)/100);
}
}
Thanks for all your attempts.The problem was actually in the Main Activity.
The following is the correct code
final Handler handler = new Handler();
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
for(int j=0;j<19;j++){
todays.set(j, todays.get(j+1));
}
Random diceRoller = new Random();
todays.set(19, diceRoller.nextInt(100)*10+1);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
bargraph.setData(todays);
}
});
}
});
I had not written the runOnUiThread at first...My bad...
I am trying to implement the spinning activity similar to the the one I have placed below in Android. I believe I should use the ProgressDialog. My issue arises from how to actually manipulate the ProgressDialog to appear like the activity indicator.
Any thoughts are welcome. A link to an example would even be better.
Thanks.
REEDIT:
myProgress.java
public class myProgress extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProgressDialog d = (ProgressDialog)findViewById(R.id.progres);
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/progres"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<ProgressBar
android:id="#+id/progressBar"
android:indeterminate="true"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
I wrote my own custom LoadingIndicatorView.
It consists of two files:
LoadingIndicatorBarView
LoadingIndicatorView
Pros:
Programmatically created, no PNG antics meaning scalable and crisp :D
Customizable bar colors and corner radius (if you understand my code)
Cons:
Not as performant as the iOS version (I'm just a beginner Android developer coming from iOS background, what do you expect?) :P
Disclaimer:
Don't blame me if your project blows up, I'm putting this as free public domain code.
You'll notice my coding style and structure resemble my iOS programming codes a lot. I do everything programmatically, no XML if I can get away with it.
How to use this Loading Indicator
After you've copied and pasted all three class source codes into their Java file, you want to use the LoadingIndicatorView class, you shouldn't need to touch the other class, unless you want to customise the colour or rounded corner of each bar.
Create an instance of LoadingIndicatorView like this in your Activity:
import com.companyName.myApplication.views.LoadingIndicatorView;
public class MyActivity extends AppCompatActivity
{
public mainLayout RelativeLayout;
...
public LoadingIndicatorView loadingIndicator;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
initViews();
initLayouts();
addViews();
}
public void initViews()
{
mainLayout = new RelativeLayout(this);
mainLayout.setBackgroundColor(Color.BLACK);
...
// ---------------------------------------------------
// 40 here is the radius of the circle
// try and use multiples of 2, e.g. 40, 60, 80 etc
// ---------------------------------------------------
loadingIndicator = new LoadingIndicatorView(this, 40);
// hide until ready to start animating
loadingIndicator.setAlpha(0.0f);
}
public void initLayouts()
{
...
// Need API level 17 for this, set in your AndroidManifeset.xml
mainLayout.setId(View.generateViewId());
loadingIndicator.setId(View.generateViewId());
RelativeLayout.LayoutParams loadingIndicatorLayoutParams = new RelativeLayout.LayoutParams(
(int)(loadingIndicator.radius * 2.0f),
(int)(loadingIndicator.radius * 2.0f)
);
loadingIndicatorLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
loadingIndicator.setLayoutParams(loadingIndicatorLayoutParams);
}
public void addViews()
{
...
mainLayout.addView(loadingIndicator);
setContentView(mainLayout);
}
}
Once you're ready to show it, e.g. in a button click listener, then you call:
loadingIndicator.startAnimating();
When you want to stop and hide the indicator, call:
loadingIndicator.stopAnimating();
You end up with something like this:
LoadingIndicatorView.java
package com.companyName.myApplication.views;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.RelativeLayout;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by Zhang on 11/02/16.
*/
public class LoadingIndicatorView extends RelativeLayout
{
private Context context;
private int numberOfBars;
public ArrayList<LoadingIndicatorBarView> arrBars;
public float radius;
private boolean isAnimating;
private int currentFrame;
private final Handler handler = new Handler();
private Runnable playFrameRunnable;
public LoadingIndicatorView(Context context, float radius)
{
super(context);
this.context = context;
this.radius = radius;
this.numberOfBars = 12;
initViews();
initLayouts();
addViews();
spreadBars();
}
public void initViews()
{
arrBars = new ArrayList<LoadingIndicatorBarView>();
for(int i = 0; i < numberOfBars; i++)
{
LoadingIndicatorBarView bar = new LoadingIndicatorBarView(context, radius / 10.0f);
arrBars.add(bar);
}
}
public void initLayouts()
{
for(int i = 0; i < numberOfBars; i++)
{
LoadingIndicatorBarView bar = arrBars.get(i);
bar.setId(View.generateViewId());
RelativeLayout.LayoutParams barLayoutParams = new RelativeLayout.LayoutParams(
(int)(radius / 5.0f),
(int)(radius / 2.0f)
);
barLayoutParams.addRule(ALIGN_PARENT_TOP);
barLayoutParams.addRule(CENTER_HORIZONTAL);
bar.setLayoutParams(barLayoutParams);
}
}
public void addViews()
{
for(int i = 0; i < numberOfBars; i++)
{
LoadingIndicatorBarView bar = arrBars.get(i);
addView(bar);
}
}
public void spreadBars()
{
int degrees = 0;
for(int i = 0; i < arrBars.size(); i++)
{
LoadingIndicatorBarView bar = arrBars.get(i);
rotateBar(bar, degrees);
degrees += 30;
}
}
private void rotateBar(LoadingIndicatorBarView bar, float degrees)
{
RotateAnimation animation = new RotateAnimation(0, degrees, radius / 10.0f, radius);
animation.setDuration(0);
animation.setFillAfter(true);
bar.setAnimation(animation);
animation.start();
}
public void startAnimating()
{
setAlpha(1.0f);
isAnimating = true;
playFrameRunnable = new Runnable()
{
#Override
public void run()
{
playFrame();
}
};
// recursive function until isAnimating is false
playFrame();
}
public void stopAnimating()
{
isAnimating = false;
setAlpha(0.0f);
invalidate();
playFrameRunnable = null;
}
private void playFrame()
{
if(isAnimating)
{
resetAllBarAlpha();
updateFrame();
handler.postDelayed(playFrameRunnable, 0);
}
}
private void updateFrame()
{
if (isAnimating)
{
showFrame(currentFrame);
currentFrame += 1;
if (currentFrame > 11)
{
currentFrame = 0;
}
}
}
private void resetAllBarAlpha()
{
LoadingIndicatorBarView bar = null;
for (int i = 0; i < arrBars.size(); i++)
{
bar = arrBars.get(i);
bar.setAlpha(0.5f);
}
}
private void showFrame(int frameNumber)
{
int[] indexes = getFrameIndexesForFrameNumber(frameNumber);
gradientColorBarSets(indexes);
}
private int[] getFrameIndexesForFrameNumber(int frameNumber)
{
if(frameNumber == 0)
{
return indexesFromNumbers(0, 11, 10, 9);
}
else if(frameNumber == 1)
{
return indexesFromNumbers(1, 0, 11, 10);
}
else if(frameNumber == 2)
{
return indexesFromNumbers(2, 1, 0, 11);
}
else if(frameNumber == 3)
{
return indexesFromNumbers(3, 2, 1, 0);
}
else if(frameNumber == 4)
{
return indexesFromNumbers(4, 3, 2, 1);
}
else if(frameNumber == 5)
{
return indexesFromNumbers(5, 4, 3, 2);
}
else if(frameNumber == 6)
{
return indexesFromNumbers(6, 5, 4, 3);
}
else if(frameNumber == 7)
{
return indexesFromNumbers(7, 6, 5, 4);
}
else if(frameNumber == 8)
{
return indexesFromNumbers(8, 7, 6, 5);
}
else if(frameNumber == 9)
{
return indexesFromNumbers(9, 8, 7, 6);
}
else if(frameNumber == 10)
{
return indexesFromNumbers(10, 9, 8, 7);
}
else
{
return indexesFromNumbers(11, 10, 9, 8);
}
}
private int[] indexesFromNumbers(int i1, int i2, int i3, int i4)
{
int[] indexes = {i1, i2, i3, i4};
return indexes;
}
private void gradientColorBarSets(int[] indexes)
{
float alpha = 1.0f;
LoadingIndicatorBarView barView = null;
for(int i = 0; i < indexes.length; i++)
{
int barIndex = indexes[i];
barView = arrBars.get(barIndex);
barView.setAlpha(alpha);
alpha -= 0.125f;
}
invalidate();
}
}
LoadingIndicatorBarView.java
package com.companyName.myApplication.views;
import android.content.Context;
import android.graphics.Color;
import android.widget.RelativeLayout;
import com.companyName.myApplication.helper_classes.ToolBox;
/**
* Created by Zhang on 11/02/16.
*/
public class LoadingIndicatorBarView extends RelativeLayout
{
private Context context;
private float cornerRadius;
public LoadingIndicatorBarView(Context context, float cornerRadius)
{
super(context);
this.context = context;
this.cornerRadius = cornerRadius;
initViews();
}
public void initViews()
{
setBackground(ToolBox.roundedCornerRectWithColor(
Color.argb(255, 255, 255, 255), cornerRadius));
setAlpha(0.5f);
}
public void resetColor()
{
setBackground(ToolBox.roundedCornerRectWithColor(
Color.argb(255, 255, 255, 255), cornerRadius));
setAlpha(0.5f);
}
}
Toolbox.java
package com.companyName.myApplication.helper_classes;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
/**
* Created by Zhang on 3/02/16.
*/
public class ToolBox
{
private static ToolBox instance;
public Context context;
private ToolBox()
{
}
public synchronized static ToolBox getInstance()
{
if(instance == null)
{
instance = new ToolBox();
}
return instance;
}
public static ShapeDrawable roundedCornerRectOutlineWithColor(int color, float cornerRadius,
float strokeWidth)
{
float[] radii = new float[] {
cornerRadius, cornerRadius,
cornerRadius, cornerRadius,
cornerRadius, cornerRadius,
cornerRadius, cornerRadius
};
RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);
ShapeDrawable shape = new ShapeDrawable();
shape.getPaint().setColor(color);
shape.setShape(roundedCornerShape);
shape.getPaint().setStrokeWidth(strokeWidth);
shape.getPaint().setStyle(Paint.Style.STROKE);
return shape;
}
public static ShapeDrawable roundedCornerRectWithColor(int color, float cornerRadius)
{
float[] radii = new float[] {
cornerRadius, cornerRadius,
cornerRadius, cornerRadius,
cornerRadius, cornerRadius,
cornerRadius, cornerRadius
};
RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);
ShapeDrawable shape = new ShapeDrawable();
shape.getPaint().setColor(color);
shape.setShape(roundedCornerShape);
return shape;
}
public static ShapeDrawable roundedCornerRectWithColor(int color, float topLeftRadius, float
topRightRadius, float bottomRightRadius, float bottomLeftRadius)
{
float[] radii = new float[] {
topLeftRadius, topLeftRadius,
topRightRadius, topRightRadius,
bottomRightRadius, bottomRightRadius,
bottomLeftRadius, bottomLeftRadius
};
RoundRectShape roundedCornerShape = new RoundRectShape(radii, null, null);
ShapeDrawable shape = new ShapeDrawable();
shape.getPaint().setColor(color);
shape.setShape(roundedCornerShape);
return shape;
}
public static int getScreenWidth()
{
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight()
{
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
public static int getScreenOrientation(Context context)
{
return context.getResources().getConfiguration().orientation;
}
public static boolean isLandscapeOrientation(Context context)
{
return getScreenOrientation(context) == Configuration.ORIENTATION_LANDSCAPE;
}
}
This Toolbox class is my convenience helper class to create rounded corner shapes etc in all my projects.
Hope that helps :D
this is how i achieve it
here is the code
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_LOADING:
final Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.loading);
dialog.setCancelable(true);
dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//onBackPressed();
}
});
return dialog;
default:
return null;
}
};
here is the loading.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/progres"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<ProgressBar
android:indeterminate="true"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
call the dialog with
showDialog(DIALOG_LOADING);
hide it using
dismissDialog(DIALOG_LOADING);
UPDATE
if you want and custom indicator you can do the following in the layout.xml.
replace the ProgressBar with an ImageView
set the background of the ImageView to a AnimationDrawable
you can start the animation in onPrepareDialog
You are looking for progressDialog i believe. This link can you set you start with it.
http://www.helloandroid.com/tutorials/using-threads-and-progressdialog
pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
false);
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
tv.setText(pi_string);
}
};
Just look at this library. IOSDialog/Spinner library
It is very easy to use and solves your problem. With it, you can easily create and use spinner like in IOS.
The example of code:
final IOSDialog dialog1 = new IOSDialog.Builder(IOSDialogActivity.this)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
dialog0.show();
}
})
.setDimAmount(3)
.setSpinnerColorRes(R.color.colorGreen)
.setMessageColorRes(R.color.colorAccent)
.setTitle(R.string.standard_title)
.setTitleColorRes(R.color.colorPrimary)
.setMessageContent("My message")
.setCancelable(true)
.setMessageContentGravity(Gravity.END)
.build();
Result
final IOSDialog dialog0 = new IOSDialog.Builder(IOSDialogActivity.this)
.setTitle("Default IOS bar")
.setTitleColorRes(R.color.gray)
.build();
Result: stadard IOS Dialog