Filters.java
public class Filters extends Activity implements OnSeekBarChangeListener{
private SeekBar PRICEbar,DISTANCEbar, RATINGbar; // declare seekbar object variable
// declare text label objects
private TextView PRICEtextProgress,DISTANCEtextProgress, RATINGtextProgress;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// load the layout
setContentView(R.layout.filters);
PRICEbar = (SeekBar)findViewById(R.id.PRICEseekBarID); // make seekbar object
PRICEbar.setOnSeekBarChangeListener(this);
PRICEbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
PRICEtextProgress = (TextView)findViewById(R.id.PRICEtextViewProgressID);
PRICEtextProgress.setText("Price:: Rs "+progress);
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (seekBar == PRICEbar)
PRICEtextProgress.setText("Price:: Rs "+progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
filters.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/relativeLayoutforPRICE"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/PRICEtextViewProgressID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Price"
android:textAppearance="?android:attr/textAppearanceLarge" >
</TextView>
<SeekBar
android:id="#+id/PRICEseekBarID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="26dp"
android:max="100" >
</SeekBar>
</RelativeLayout>
</LinearLayout>
I have an output like this::
How to modify my code to get initial and final values in the seek bar as in figure below?
You have already defined max value of seekbar
android:max="100"
Now you need to add two textviews on left and right of seekbar. Use Relative layout and align both textviews Left and Right to the parent.
Brontok's hint solved my problem. I just had to alter the XML. I want to share the result here:
<RelativeLayout
android:id="#+id/relativeLayoutforPRICE"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/PRICEtextViewProgressID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Price"
android:textAppearance="?android:attr/textAppearanceLarge" >
</TextView>
<SeekBar
android:id="#+id/PRICEseekBarID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="26dp"
android:max="100" >
</SeekBar>
<TextView
android:id="#+id/PRICEinitialvaluetextID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/PRICEseekBarID"
android:text="Rs 0" >
</TextView>
<TextView
android:id="#+id/PRICEinitialvaluetextID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/PRICEseekBarID"
android:text="Rs 100" />
</RelativeLayout>
First, I think you should extend SeekBar.
Second, call canvas.drawText() in onDraw() method to draw text before SeekBar and after SeekBar.
This way you can refresh the textView in your onDraw method callback
check it out, You implemented OnSeekBarChangeListener created methods, and set
public class Filters extends Activity implements OnSeekBarChangeListener{
PRICEbar.setOnSeekBarChangeListener(this);
and next line you override it with new OnSeekBarChangeListener
PRICEbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
you can delete implements OnSeekBarChangeListener and these 3 empty methods from your activity (onSeekBarChange, onStartTracking, onStopTracking)
just for fun with an empty linear layout in main.xml
a sample with seekbar
import android.app.*;
import android.os.*;
import android.view.*;
import android.content.*;
import android.graphics.*;
import android.graphics.Color.*;
import android.graphics.drawable.*;
import android.graphics.drawable.shapes.*;
import android.widget.*;
import android.widget.ProgressBar;
import android.text.*;
//import org.apache.http.impl.conn.*;
import android.util.*;
import android.view.View.*;
import android.widget.SeekBar.*;
public class MainActivity extends Activity {
public int angle=30;
#Override
//CustomDrawableView customDrawableView;
LinearLayout myLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myLayout = findViewById(R.id.linear_layout);
//setContentView(customDrawableView);
/* TextView text1 = new TextView(this);
text1.setText(R.string.hello_world);
myLayout.addView(text1);
*/
final TextView text2 = new TextView(this);
text2.setText("30");
myLayout.addView(text2);
SeekBar seek = new SeekBar(this);
//seek.setMin(2);
seek.setMax(180);
seek.setProgress(30);
myLayout.addView(seek);
final CustomDrawableView customDrawableView = new CustomDrawableView(this);
myLayout.addView(customDrawableView);
customDrawableView.setBackgroundColor(0x00888888);
seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
public void onProgressChanged(SeekBar seek,int value,boolean usr){
angle = value;
if (angle<=2) angle = 2;
text2.setText(String.valueOf(value));
customDrawableView.invalidate();
}
public void onStartTrackingTouch(SeekBar seek){
}
public void onStopTrackingTouch(SeekBar seek){
}
});
//customDrawableView.setRotationX(45);
}; // MainActivity_onCreate
public class CustomDrawableView extends View {
private int n=16;
private ShapeDrawable[] drws = new ShapeDrawable[4*n];
protected Canvas canvas;
public CustomDrawableView(Context context) {
super(context);
setContentDescription(context.getResources().getString(
R.string.my_view_desc));
angle = 30;
};
protected void onDraw(Canvas oCanvas) {
canvas = oCanvas;
show();
}; // onDraw
public void show() {
int cx = canvas.getWidth()/2;
int cy = canvas.getHeight()/2;
int color = Color.argb(0x88,0x00,0x99,0xff);
int stp;
for (int s=0;s<180;s+=angle){
canvas.rotate(angle,cx,cy);
for (int i=0;i<=15;i++){
stp = 29 - i;
color = Color.argb(i*10, i*17, 0xaa, 0xff - i*10);
drws[i] = new ShapeDrawable(new OvalShape());
drws[i].getPaint().setColor(color);
drws[i].setBounds(cx+stp*i, cy+10, cx+30+stp*i, cy+20);
drws[n+i] = new ShapeDrawable(new OvalShape());
drws[n+i].getPaint().setColor(color);
drws[n+i].setBounds(cx+10+stp*i, cy, cx+20+stp*i, cy+30);
drws[2*n+i] = new ShapeDrawable(new OvalShape());
drws[2*n+i].getPaint().setColor(color);
drws[2*n+i].setBounds(cx-stp*i-30, cy-20, cx-stp*i, cy-10);
drws[3*n+i] = new ShapeDrawable(new OvalShape());
drws[3*n+i].getPaint().setColor(color);
drws[3*n+i].setBounds(cx-stp*i-20, cy-30, cx-stp*i-10, cy);
canvas.rotate(22.5f,cx,cy);
drws[i].draw(canvas);
drws[n+i].draw(canvas);
drws[2*n+i].draw(canvas);
drws[3*n+i].draw(canvas);
}
canvas.rotate(angle,cx,cy);
}
}
}; // CustomDrawableView
}; // MainActivity
Related
I have a problem with adding my surface view to a linear layout, I have tried the already available answers and still cant seem to figure it out. My aim is to render an animation at the bottom of my login screen when my the next button is clicked. I tried adding a linear Layout to the Screen and then adding my gameView object on to that.
This is the loginActivity and game View Class for clarity I've also added the xml.
`package com.example.Combat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.*;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
public GameView gameView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setting the font
Typeface myTypeFace = Typeface.createFromAsset(getAssets(),"Typo Oxin free promo.ttf");
TextView myTextView = (TextView) findViewById(R.id.nameTextView);
myTextView.setTypeface(myTypeFace);
gameView = new GameView(this);
// LinearLayout.LayoutParams lp =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// lp.gravity= Gravity.BOTTOM;
LinearLayout myLayout = new LinearLayout(this);
myLayout.findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);
}
#Override
public void onResume(){
super.onResume();
gameView.resume();
}
#Override
protected void onPause(){
super.onPause();
gameView.pause();
}
public void beginMotion(View view) {
GameView.isMoving=!GameView.isMoving;
// startActivity(new Intent(getApplicationContext(),transitionActivity.class));
}
}
`
package com.example.Combat;
import android.content.Context;
import android.graphics.*;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by vmuser on 2017/05/05.
*/
public class GameView extends SurfaceView implements Runnable{
private Thread gameThread;
private SurfaceHolder ourHolder;
public static volatile boolean playing=false;
private Canvas canvas;
private Bitmap bitmapRunningMan;
public static boolean isMoving=false;
private float runSpeedPerSecond = 150;
//LinearLayout screen=(LinearLayout)findViewById(R.id.theScreen);
private float manXPos = 1020, manYPos = 950;
private int frameWidth = 230, frameHeight = 274;
private int frameCount = 6;
private int currentFrame = 0;
private long fps;
private long timeThisFrame;
private long lastFrameChangeTime = 0;
private int frameLengthInMillisecond = 60;
private Rect frameToDraw = new Rect(0, 0, frameWidth, frameHeight);
private RectF whereToDraw = new RectF(manXPos, manYPos, manXPos + frameWidth, frameHeight);
public GameView(Context context) {
super(context);
ourHolder = getHolder();
bitmapRunningMan = BitmapFactory.decodeResource(getResources(),
R.drawable.perfectsoldier);
bitmapRunningMan = Bitmap.createScaledBitmap(bitmapRunningMan,
frameWidth * frameCount, frameHeight, false);
}
#Override
public void run() {
while (playing) {
long startFrameTime = System.currentTimeMillis();
update();
this.draw();
Log.d("theOne","its Happennig");
timeThisFrame = System.currentTimeMillis() - startFrameTime;
if (timeThisFrame >= 1) {
fps = 1000 / timeThisFrame;
}
}
}
public void update() {
if (isMoving) {
manXPos = manXPos - runSpeedPerSecond / fps;
if (manXPos > 0) {
//manYPos += (int) frameHeight;
//manXPos = 10;
isMoving=false;
}
if (manYPos + frameHeight > 0) {
// manYPos = 10;
isMoving=false;
}
}
}
public void manageCurrentFrame() {
long time = System.currentTimeMillis();
if (isMoving) {
if (time > lastFrameChangeTime + frameLengthInMillisecond) {
lastFrameChangeTime = time;
currentFrame++;
if (currentFrame >= frameCount) {
currentFrame = 0;
}
}
}
frameToDraw.left = currentFrame * frameWidth;
frameToDraw.right = frameToDraw.left + frameWidth;
}
public void draw() {
if (ourHolder.getSurface().isValid()) {
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
whereToDraw.set((int) manXPos, (int) manYPos, (int) manXPos
+ frameWidth, (int) manYPos + frameHeight);
manageCurrentFrame();
canvas.drawBitmap(bitmapRunningMan, frameToDraw, whereToDraw, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch(InterruptedException e) {
Log.e("ERR", "Joining Thread");
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
// public boolean onTouchEvent(MotionEvent event) {
// switch (event.getActionMasked() & MotionEvent.ACTION_MASK) {
// case MotionEvent.ACTION_DOWN :
// isMoving = !isMoving;
// break;
// }
//
// return true;
// }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusableInTouchMode="true"
android:color="#000000"
android:weightSum="1" android:background="#ffffff" android:orientation="vertical"
android:id="#+id/theScreen">
<ImageView
android:layout_width="113dp"
android:layout_height="130dp"
android:src="#drawable/thelogo"
android:id="#+id/imageView" android:layout_gravity="center_horizontal"/>
<TextView
android:layout_width="145dp"
android:layout_height="49dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="combat"
android:textSize="30sp"
android:textColor="#000000"
android:id="#+id/nameTextView" android:layout_gravity="right" android:layout_weight="0.06"/>
<EditText
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Username"
android:textColorHint="#808080"
android:textColor="#22272a"
android:id="#+id/userNameEditText" android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="261dp"
android:layout_height="wrap_content"
android:text="Next"
android:drawableRight="#drawable/thearrow"
android:textColor="#000000"
android:onClick="beginMotion"
android:id="#+id/NextButton" android:layout_gravity="center_horizontal" android:background="#638455"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Create an account"
android:id="#+id/textView" android:layout_gravity="center_horizontal" android:layout_weight="0.07"
android:textColor="#22272A"/>
<LinearLayout
android:id="#+id/gameLayoutView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
</LinearLayout>
</LinearLayout>
You haven't attached myLayout to the activity main layout that you earlier set on setContentView(R.layout.main).
Instead of:
LinearLayout myLayout = new LinearLayout(this);
myLayout.findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);
You should write this:
LinearLayout myLayout = (LinearLayout) findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);
Let's say I have a custom view inside an activity and a TextView just below that custom view. I would like to change the TextView's text once the custom view was clicked but I seem to get a null pointer when I use findViewById(), so how can I do that?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.yuvaleliav1gmail.quoridor_ye.MainActivity"
android:background="#dd7d23">
<com.yuvaleliav1gmail.quoridor_ye.ComBoardView
android:layout_width="900px"
android:layout_height="900px"
android:id="#+id/bview"
android:background="#drawable/game_board"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioGroup"
android:layout_below="#+id/bview"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Move Pawn"
android:id="#+id/radioPawn"
android:checked="true"
android:onClick="radioButtonClick"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set VERTICAL Wall"
android:id="#+id/verticalRdio"
android:checked="false"
android:onClick="radioButtonClick"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set HORIZONTAL Wall"
android:id="#+id/horizontalRdio"
android:checked="false"
android:onClick="radioButtonClick"/>
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Your turn"
android:id="#+id/turnText34"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/radioGroup"
android:layout_alignLeft="#+id/bview"
android:layout_alignStart="#+id/bview" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Your walls left: "
android:id="#+id/yourWallsText"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/turnText34"
android:layout_alignLeft="#+id/turnText34"
android:layout_alignStart="#+id/turnText34" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="10"
android:id="#+id/yourNumText"
android:layout_gravity="center_horizontal"
android:layout_alignTop="#+id/yourWallsText"
android:layout_toRightOf="#+id/yourWallsText"
android:layout_toEndOf="#+id/yourWallsText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Opponent's walls left:"
android:id="#+id/opWallsText"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/yourWallsText"
android:layout_alignLeft="#+id/yourWallsText"
android:layout_alignStart="#+id/yourWallsText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="10"
android:id="#+id/opNumText"
android:layout_gravity="center_horizontal"
android:layout_alignTop="#+id/opWallsText"
android:layout_toRightOf="#+id/opWallsText"
android:layout_toEndOf="#+id/opWallsText" />
</RelativeLayout>
comBoardView is the custom view's class
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
public class ComBoardView extends View {
private static final int ROWS = 9;
private static final int COLUMNS = 9;
public static Context con;
Paint paint;
GameService game;
TextView turns;
public static Point size = new Point();
/*
* constructor
*/
public ComBoardView(Context context, AttributeSet attrs) {
super(context, attrs);
con = context;
paint = new Paint();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getSize(size);
turns = (TextView) findViewById(R.id.turnText34);
}
/*
*/
public boolean onTouchEvent( MotionEvent event ) {
game = GameService.getInstance();
int x = (int)event.getX() / 100;
int y = (int)event.getY() / 100;
if ( event.getAction() != MotionEvent.ACTION_UP )
return true;
if(game.movePawn){
if(game.turn % 2 == 0){
if(game.isLegalMove(game.ai.MyLocation , y * ROWS + x)){
game.board.ClrPlayer(game.ai);
game.ai.MyLocation = y * ROWS + x;
game.board.SetPlayer(game.ai);
if(turns != null){
turns.setText("white's turn");
}
game.turn++;
}
}
else{
if(game.isLegalMove(game.player.MyLocation , y * ROWS + x)){
game.board.ClrPlayer(game.player);
game.player.MyLocation = y * ROWS + x;
game.board.SetPlayer(game.player);
if(turns != null){
turns.setText("black's turn");
}
game.turn++;
}
}
}
else {
if(((int)event.getX() % 100) < 50) x--;
if(((int)event.getY() % 100) < 50) y--;
if(game.setHWall){
game.board.SetHWall(y,x);
game.turn++;
}
else{
game.board.SetVWall(y,x);
game.turn++;
}
}
return true;
}
public void RestartTimer() {
new CountDownTimer(3500, 1000) {
public void onTick(long millisUntilFinished) {
final Toast toast = Toast.makeText(con, "restarting in: " + millisUntilFinished / 1000, Toast.LENGTH_LONG);
toast.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 1000);
}
public void onFinish() {
}
}.start();
}
protected void onDraw(Canvas canvas) {
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
GameService.getInstance().onDraw(canvas, paint);
}
}
and game is the activity's class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import java.util.Timer;
public class Game extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Timer timer = new Timer();
GameUpdateTimer ut = new GameUpdateTimer();
ut.boardView = (ComBoardView)this.findViewById(R.id.bview);
timer.schedule(ut, 200, 200);
RadioButton pawn = (RadioButton)findViewById(R.id.radioPawn);
RadioButton hWall = (RadioButton)findViewById(R.id.horizontalRdio);
RadioButton vWall = (RadioButton)findViewById(R.id.verticalRdio);
final GameService g = GameService.getInstance();
pawn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
g.movePawn = true;
g.setHWall = false;
}});
hWall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
g.movePawn = false;
g.setHWall = true;
}
});
vWall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
g.movePawn = false;
g.setHWall = false;
}
});
}
}
You can't call turns = (TextView) findViewById(R.id.turnText34); from your custom view, it will always return Null because TextView exist in the activity xml and not in ComBoardView.
What you can do, is to instantiate your TextView in the activity, then add a clickListener to your ComBoardView.
TextView turns;
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
turns = (TextView) findViewById(R.id.turnText34);
ut.boardView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
turns.setText("ComBoardView was clicked!");
}});
//...
}
I have made a demo project for image rotation in seekbar progresschange. I have successfully done it on button change but its not working on seekbar change. Here is what I tried:
xml
<ImageView
android:id="#+id/iv_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/enr" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:max="360"
android:padding="1dp"
android:progress="0" />
<Button
android:id="#+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/seekbar"
android:layout_centerHorizontal="true"
android:text="Rotate" />
code
public class MainActivity extends Activity implements OnSeekBarChangeListener {
ImageView iv_image;
SeekBar seekbar;
Bitmap source;
float angle = 0;
Button buttonClick;
Bitmap rotatedImage;
static Matrix matrix;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
buttonClick = (Button) findViewById(R.id.bt);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
angle += 90;
iv_image.buildDrawingCache();
source = iv_image.getDrawingCache();
rotatedImage = rotateImage(source, angle);
iv_image.setImageBitmap(rotatedImage);
}
});
}
void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setOnSeekBarChangeListener(this);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
angle = progress;
iv_image.buildDrawingCache();
source = iv_image.getDrawingCache();
rotatedImage = rotateImage(source, angle);
iv_image.setImageBitmap(null);
iv_image.setImageBitmap(rotatedImage);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public static Bitmap rotateImage(Bitmap sourceImage, float angle) {
matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(sourceImage, 0, 0, sourceImage.getWidth(),
sourceImage.getHeight(), matrix, true);
}
}
You forgot to attach OnSeekBarChangeListener to your SeekBar:
void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setOnSeekBarChangeListener(this); // <-----
}
I suggest you use the Picasso library by Square. It will be much simpler and straightforward for this need here
I have a seekbar above which i have a placed a textview which displays the value of the seekbar movement. My problem is the alignment of the Textview and the Seekbar initially are same but as dragging the alignment changes i have attached screen shots and code.
XML File
</LinearLayout>
<RelativeLayout
android:id="#+id/sliderAndPoints_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="top"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_minBonApps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:text="0" />
<TextView
android:id="#+id/tv_max_BonApps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="7000" />
<SeekBar
android:id="#+id/sb_changes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_toLeftOf="#+id/tv_max_BonApps"
android:layout_toRightOf="#+id/tv_minBonApps"
android:max="70"
android:maxHeight="2dip"
android:paddingLeft="8dp"
android:progressDrawable="#drawable/seek_bar"
android:thumb="#drawable/panier_vide_btn" />
</RelativeLayout>
</LinearLayout>
Java File
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#SuppressLint("NewApi")
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
currentBonsPoints = progress * 100;
if (progress < 3500) {
int xPos = (((seekbar.getRight() - seekbar.getLeft()) * seekbar
.getProgress()) / seekbar.getMax())
+ seekbar.getLeft();
layout_bouns.setPadding(xPos - 25, 0, 0, 0);
bonsCount.setText("" + (progress * 100));
} else if (progress >= 3500 && progress < 4900) {
int xPos = (((seekbar.getRight() - seekbar.getLeft()) * seekbar
.getProgress()) / seekbar.getMax())
+ seekbar.getLeft();
layout_bouns.setPadding(xPos - 34, 0, 0, 0);
bonsCount.setText("" + (progress * 100));
} else {
int xPos = (((seekbar.getRight() - seekbar.getLeft()) * seekbar
.getProgress()) / seekbar.getMax())
+ seekbar.getLeft();
layout_bouns.setPadding(xPos - 37, 0, 0, 0);
bonsCount.setText("" + (progress * 100));
}
}
});
package com.example.seekbarwithtextviewsample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsoluteLayout;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView mTxvSeekBarValue;
SeekBar mSkbSample;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTxvSeekBarValue = (TextView) this.findViewById(R.id.txvSeekBarValue);
mSkbSample = (SeekBar) this.findViewById(R.id.skbSample);
mSkbSample.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
ShowSeekValue((int)event.getX(), mTxvSeekBarValue.getTop());
mTxvSeekBarValue.setVisibility(View.VISIBLE);
}
else if(event.getAction() == MotionEvent.ACTION_MOVE)
{
ShowSeekValue((int)event.getX(), mTxvSeekBarValue.getTop());
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
mTxvSeekBarValue.setVisibility(View.INVISIBLE);
}
return false;
}
});
}
private void ShowSeekValue(int x, int y)
{
if(x > 0 && x < mSkbSample.getWidth())
{
AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, x, y);
mTxvSeekBarValue.setLayoutParams(lp);
mTxvSeekBarValue.setText(""+mSkbSample.getProgress());
}
}
}
and in the layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- Main context -->
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SeekBar android:id="#+id/skbSample"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="25dp"
android:max="10000">
</SeekBar>
</LinearLayout>
<!-- For display value -->
<AbsoluteLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/txvSeekBarValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:background="#drawable/infowindow"
>
</TextView>
</AbsoluteLayout>
</RelativeLayout>
You will get what you are looking for...
My problem is probably simple - there are many apps out there that accomplish what I am trying to do.
I have a Relative Layout with a row of buttons and then beneath this I want to draw on a canvas.
My problem is that Canvas draws over the buttons or instead of the buttons so all I end up with is a shape.
This is my code:
package com.android.phil.graphtoggle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends Activity
{
public int graph_toggle = 0;
public int data_toggle=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton graph_toggle_button = (ImageButton) findViewById(R.id.graph_toggle);
final ImageButton graph_settings_button = (ImageButton) findViewById(R.id.graph_type);
final ImageButton data_toggle_button = (ImageButton) findViewById(R.id.data_toggle);
CustomDrawableView mCustomDrawableView;
mCustomDrawableView = new CustomDrawableView(this);
setContentView(mCustomDrawableView);
graph_toggle_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
if (graph_toggle==2)
{
graph_toggle=0;
}
else
{
graph_toggle++;
}
if (graph_toggle==0)
{
graph_settings_button.setImageResource(R.drawable.close);
}
if (graph_toggle==1)
{
graph_settings_button.setImageResource(R.drawable.ohlc_bars);
}
if(graph_toggle==2)
{
graph_settings_button.setImageResource(R.drawable.candles);
}
}
});
data_toggle_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
if (data_toggle==2)
{
data_toggle=0;
}
else
{
data_toggle++;
}
if (data_toggle==0)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_daily);
}
if (data_toggle==1)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_weekly);
}
if(data_toggle==2)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_monthly);
}
}
});
}
public class CustomDrawableView extends View
{
private ShapeDrawable mDrawable;
public CustomDrawableView(Context context)
{
super(context);
int x = 10;
int y = 100;
int width = 300;
int height = 50;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas)
{
mDrawable.draw(canvas);
}
}
}
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:id="#+id/relativeLayout1" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent">
<ImageButton
android:layout_height="40dip"
android:layout_width="40dip"
android:id="#+id/graph_toggle"
android:src="#drawable/graph_toggle"
android:layout_alignParentLeft="true"
></ImageButton>
<ImageButton
android:layout_height="40dip"
android:layout_width="40dip"
android:id="#+id/graph_type"
android:src="#drawable/close"
android:layout_toRightOf="#+id/graph_toggle"
></ImageButton>
<ImageButton
android:layout_height="40dip"
android:layout_width="40dip"
android:id="#+id/data_toggle"
android:src="#drawable/ohlc_bars_daily"
android:layout_toRightOf="#+id/graph_type"
></ImageButton>
<ImageButton
android:layout_height="40dip"
android:layout_width="40dip"
android:id="#+id/data_toggle1"
android:src="#drawable/ohlc_bars_daily"
android:layout_toRightOf="#+id/data_toggle"
></ImageButton>
<ImageButton
android:layout_height="40dip"
android:layout_width="40dip"
android:id="#+id/data_toggle2"
android:src="#drawable/ohlc_bars_daily"
android:layout_toRightOf="#+id/data_toggle1"
></ImageButton>
<ImageButton
android:layout_height="40dip"
android:layout_width="40dip"
android:id="#+id/data_toggle3"
android:src="#drawable/ohlc_bars_daily"
android:layout_toRightOf="#+id/data_toggle2"
></ImageButton>
<ImageButton
android:layout_height="40dip"
android:layout_width="40dip"
android:id="#+id/data_toggle4"
android:src="#drawable/ohlc_bars_daily"
android:layout_toRightOf="#+id/data_toggle3"
></ImageButton>
</RelativeLayout>
You're substituting your whole xml layout with your custom view when you call:
setContentView(mCustomDrawableView);
You should rather add your custom view to the layout, something like:
RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.relativeLayout1);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(/*up to you*/);
// add here other layout params rules to make your
// custom view stay below the buttons
mCustomDrawableView.setLayoutParams(lp);
mainLayout.addView(mCustomDrawableView);
However you should also consider adding to your custom view this kind of constructor:
public CustomDrawableView(Context context, AttributeSet attrs) {
super(context, attrs);
// add other init stuff
}
so that you can use your custom view into the xml, making it easier to specify layout params, because doing it in code can be boring for a RelativeLayout.
create a class which extends the framelayout class and overwrite the onDraw function
there you can draw everything you want and it will behave like any other view