I want to programmatically scroll a RecyclerView, is it possible to do something like this?
I have the following code in a custom RecyclerView in order to dispatch a scrolling event, but I am stuck in figuring out a mock MotionEvent:
public boolean dispatchHandlerScroll(MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN: {
y = (int) e.getY();
startNestedScroll(2);
break;
}
case MotionEvent.ACTION_MOVE: {
int dY = y - ((int) e.getY());
dispatchNestedPreScroll(0, dY, null, null);
dispatchNestedScroll(0, 0, 0, dY, null);
break;
}
case MotionEvent.ACTION_UP: {
stopNestedScroll();
break;
}
}
return true;
}
Anyone have an idea?
Related
I was wondering what mistake I made in the line that is formatted like this "''" because I was wondering why my code wouldn't move back to the right to bounce back and forth between walls. I put the code that I need help in with single quotations. This is my frist time on stack, so any tips would be appreciated.
PImage invader, invader2, invader3, invader4, invader5, space, tank;
int tankX = 400;
PImage [] picArray = new PImage [7];
int invaderState = 2;
int timer = 0;
int lap = 0;
int [] alienXPos = {100, 180, 260, 340, 420, 500, 580, 660, 740, 820};
//had to add a few zeros on alienYPos otherwise the loop would bug out and wouldn't work
int[] alienYPos = {40, 140, 240, 340, 0, 0, 0, 0, 0, 0};
boolean moveLeft, moveRight;
int paddleSpeed = 3;
int gameState = 1;
String message1 = "Welcome to space invaders!";
String message2 = "Click space to start!";
boolean movingLeft, movingRight;
void setup() {
size(1000, 1000);
invader = loadImage("invader.jpg");
invader.resize(70, 50);
invader2 = loadImage("invader2.png");
invader2.resize(70, 50);
space = loadImage("space.png");
space.resize(1000, 1000);
tank = loadImage("tank.png");
tank.resize(150, 100);
}
void draw() {
background(space);
timer = millis();
if (timer-lap>800) {
lap = timer;
' **for (int m=0; m <10; m++) {
if (movingRight == false) {
alienXPos[m] += 40;
} else {
alienXPos[m] -= 40;
}
if (alienXPos [m] > 900 && movingRight == false) {
movingRight = true;
for (int l=0; l<10; l++) {
alienYPos[l] += 75;
println("movingleft : " + movingLeft);
println("Moving right : " + movingRight);
}
// if(movingLeft == false){
// alienXPos[m] -= 55;
//}
//else{
// alienXPos [m] += 40;
//}
if (movingLeft == false) {
//alienXPos[m] -=55;
} /*else {
alienXPos[m] ;
}*/
if (alienXPos[m] < 100 && movingLeft == true) {
movingLeft = false;
movingRight = true;
/*for (int l=0; l<10; l++) {
alienYPos[l] += 75;
}** '
println("movingLeft : " + movingLeft);
*/
}
}
}
/* if (alienXPos[m] > 0 && movingLeft == true) {
alienXPos[m] -= 55;
}*/
if (invaderState == 1) {
invaderState = 2;
} else {
invaderState = 1;
}
}
if (tankX > width) {
tankX = 0;
}
if (tankX < 0) {
tankX = 1000;
}
if (gameState == 1) {
drawGameState1();
} else if (gameState == 2) {
drawGameState2();
}
}
void drawGameState1() {
background(#222222);
fill(#000000);
textSize(36);
fill(130, 130, 130);
text(message1, 300, 450);
textSize(20);
text(message2, 430, 600);
}
void drawGameState2() {
background(space);
drawSpaceInvader1();
drawTank();
drawTankMovement();
}
void drawSpaceInvader1() {
for (int i=0; i< 10; i++) {
if (invaderState == 1) {
image(invader, alienXPos[i], alienYPos[0]);
image(invader, alienXPos[i], alienYPos[1]);
image(invader, alienXPos[i], alienYPos[2]);
image(invader, alienXPos[i], alienYPos[3]);
} else if (invaderState == 2) {
image(invader2, alienXPos[i], alienYPos[0]);
image(invader2, alienXPos[i], alienYPos[1]);
image(invader2, alienXPos[i], alienYPos[2]);
image(invader2, alienXPos[i], alienYPos[3]);
}
}
}
void drawTank() {
image(tank, tankX, 700);
}
void drawTankMovement() {
if (moveLeft) {
tankX -= 25;
}
if (moveRight) {
tankX += 25;
}
}
void keyPressed() {
if (gameState == 1) {
if (keyCode == 32) {
gameState = 2;
}
}
if (gameState == 2) {
if (keyCode == LEFT) {
moveLeft = true;
}
if (keyCode == RIGHT) {
moveRight = true;
}
}
}
void keyReleased() {
if (keyCode == LEFT) { // Left Key
moveLeft = false;
}
if (keyCode == RIGHT) { // Right Key
moveRight = false;
}
}
A few things:
Next time, please try and provide a minimal, reproducible example, you were almost there, but you forgot to attach the image files that you use to draw your game out. Running this code gave me errors saying I was missing a few files. I took the liberty of importing some nonsense image and reusing that as your missing assets.
Also missing from your answer is a more implicit title. I think you misunderstood the term "reformatting" code, as that generally refers to the formatting of code. To make your answer likely to be found by others with the same problem, please consider changing the title to what your question is actually about: You can't figure out why your code doesn't reverse the movement of your row of space invaders. Next time, please read this guide on how to write a proper question.
Now to answer your question:
I ran your code and noticed that movingLeft was false whilst movingRight was true. Yet your invaders seem to be running towards the left side of the screen. One of your mistakes was probably getting confused by these variables.
In your code you do
if (movingRight == false) {
alienXPos[m] += 40;
} else {
alienXPos[m] -= 40;
}
Which effectively does the opposite of what you want. In coordinates are oriented like this, assuming we have a 800x400 canvas:
So if you want your invaders to move right, you should be adding to the coordinates when the bool is true, not when it's false. Your logic which flips the invaders direction should be sound:
if (alienXPos[m] < 100 && movingLeft == true) {
movingLeft = false;
movingRight = true;
}
But since in your program due to the above logic error movingLeft is never true, this statement will never run.
One suggestion is that in the simple case of space invaders you don't really need to keep track of two seperate moving variables for each direction, after all, invaders either:
Move to the right
or
Move to the left
Thus you could ditch having two variables and just check, for example, movingRight. If that is true, the invaders should be moving to the right, and if it's false, they should be moving to the left.
I have set list border using trigger according to my requirement but when I scroll up the listview and selected view cell is gone than I scroll down when ViewCell is appearing on screen than selected border is gone
To prevent this I also created frame renderer but still ViewCell border gone.
Attached image here
class FrameHighLightRenderer : VisualElementRenderer<Frame>
{
ACanvas _canvas = null;
private FrameDrawable _frameDrawable;
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (_frameDrawable != null && e.NewElement.ClassId != null) //This block execute while any cell appearing in scroll time up/dowm
{ // I added classId =10 to identify colored/selected cell
if (e.NewElement.ClassId=="10")
{
e.NewElement.OutlineColor = Xamarin.Forms.Color.Red;
this.Invalidate();
}
else
{
e.NewElement.BackgroundColor = Xamarin.Forms.Color.TransParent;
}
}
else
{
UpdateBackground();
}
}
}
void UpdateBackground()
{
_frameDrawable = new FrameDrawable(Element, Context.ToPixels);
this.SetBackground(_frameDrawable);
}
class FrameDrawable : Drawable
{
readonly Frame _frame;
readonly Func<double, float> _convertToPixels;
public ACanvas _canvas;
bool _isDisposed;
Bitmap _normalBitmap;
public FrameDrawable(Frame frame, Func<double, float> convertToPixels)
{
_frame = frame;
_convertToPixels = convertToPixels;
frame.PropertyChanged += FrameOnPropertyChanged;
}
public override bool IsStateful
{
get { return false; }
}
public override int Opacity
{
get { return 0; }
}
public override void Draw(ACanvas canvas)
{
SetBorderColorandWidth(canvas);
}
private void SetBorderColorandWidth(ACanvas canvas)
{
int width = Bounds.Width();
int height = Bounds.Height();
if (width <= 0 || height <= 0)
{
if (_normalBitmap != null)
{
_normalBitmap.Dispose();
_normalBitmap = null;
}
return;
}
if (_normalBitmap == null || _normalBitmap.Height != height || _normalBitmap.Width != width)
{
_normalBitmap = CreateBitmap(false, width, height);
}
Bitmap bitmap = _normalBitmap;
// if(canvas)
if (InspectionQAPage._highlight_color)
{
using (var paint = new Paint { AntiAlias = true })
using (var path = new Path())
using (Path.Direction direction = Path.Direction.Cw)
using (Paint.Style style = Paint.Style.Stroke)
using (var rect = new RectF(0, 0, width, height))
{
float rx = Forms.Context.ToPixels(4);
float ry = Forms.Context.ToPixels(4);
path.AddRoundRect(rect, rx, ry, direction);
if (this._frame.OutlineColor == Xamarin.Forms.Color.Red)
{
paint.Color = Android.Graphics.Color.Red;
this._frame.ClassId = "10";
// this._frame.BackgroundColor = Xamarin.Forms.Color.Red;
// paint.SetStyle = (Paint.Style)(Resource.Style.WithBorder);
}
else
{
// paint.Reset();
paint.Color = Android.Graphics.Color.Transparent;
// this._frame.BackgroundColor = Xamarin.Forms.Color.Transparent;
}
paint.StrokeWidth = 10f; //set outline stroke
paint.SetStyle(style);
canvas.DrawPath(path, paint);
}
InspectionQAPage._highlight_color = false;
}
else
{
using (var paint = new Paint())
canvas.DrawBitmap(bitmap, 0, 0, paint);
}
// InvalidateSelf();
}
public override void SetAlpha(int alpha)
{
}
public override void SetColorFilter(ColorFilter cf)
{
}
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
if (_normalBitmap != null)
{
_normalBitmap.Dispose();
_normalBitmap = null;
}
_isDisposed = true;
}
base.Dispose(disposing);
}
protected override bool OnStateChange(int[] state)
{
return false;
}
Bitmap CreateBitmap(bool pressed, int width, int height)
{
Bitmap bitmap;
using (Bitmap.Config config = Bitmap.Config.Argb8888)
if (width <= 0 || height <= 0)
{
return null;
}
else
bitmap = Bitmap.CreateBitmap(width, height, config);
using (var canvas = new ACanvas(bitmap))
{
// DrawCanvas(canvas, width, height, pressed);
}
return bitmap;
}
void FrameOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName ||
e.PropertyName == Frame.OutlineColorProperty.PropertyName ||
e.PropertyName == Frame.CornerRadiusProperty.PropertyName)
{
try
{
if (_normalBitmap == null)
return;
int width = Bounds.Width();
int height = Bounds.Height();
if (width <= 0 || height <= 0)
{
return;
}
if (_canvas == null)
{
var canvas = new ACanvas(_normalBitmap);
_canvas = canvas;
_canvas.DrawColor(global::Android.Graphics.Color.Red, PorterDuff.Mode.Clear);
DrawCanvas(_canvas, width, height, false, sender);
}
else
{
_canvas.DrawColor(global::Android.Graphics.Color.Red, PorterDuff.Mode.Clear);
DrawCanvas(_canvas, width, height, false, sender);
}
InvalidateSelf();
}
catch (Exception ex)
{
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>" + ex);
throw;
}
}
}
public void DrawCanvas(ACanvas canvas, int width, int height, bool pressed, object sender)
{
using (var paint = new Paint { AntiAlias = true })
using (var path = new Path())
using (Path.Direction direction = Path.Direction.Cw)
using (Paint.Style style = Paint.Style.Stroke)
using (var rect = new RectF(0, 0, width, height))
{
float rx = Forms.Context.ToPixels(4);
float ry = Forms.Context.ToPixels(4);
path.AddRoundRect(rect, rx, ry, direction);
if (((Frame)sender).OutlineColor == Xamarin.Forms.Color.Red)
{
paint.Color = Android.Graphics.Color.Red;
((Frame)sender).ClassId = "10";
}
else
{
((Frame)sender).BackgroundColor = Xamarin.Forms.Color.Transparent;
}
paint.StrokeWidth = 10f; //set outline stroke
paint.SetStyle(style);
canvas.DrawPath(path, paint);
}
}
}
}
}
Currently, my program is losing focus and not processing after minimizing and unminimizing(restore/re-expose) of window.
I've added debugging code to my code to search out what is happening after you restore the window post-hitting minimize.
The Event that seems to be occurring is SDL_WINDOWEVENT_EXPOSED.
After, the window is re-expose I attempt to process it; but nothing happens. The window is unresponsive until I hit restore down.
Here is my code:
void GPE_Renderer::handle_events(SDL_Event& e)
{
//Window event occured
if( e.type == SDL_WINDOWEVENT )
{
//Caption update flag
switch( e.window.event )
{
//Get new dimensions and repaint on window size change
case SDL_WINDOWEVENT_SIZE_CHANGED:
case SDL_WINDOWEVENT_RESIZED:
if( isMinimized)
{
SDL_RestoreWindow(gpeWindow);
//SDL_SetWindowSize(gpeWindow,mWidth,mHeight);
rWidth = mWidth;
rHeight = mHeight;
isMinimized = false;
clear_renderer();
record_error("Window unminimized");
}
else
{
if( e.window.data1>0 && e.window.data2 > 0)
{
mWidth = rWidth = e.window.data1;
mHeight = rHeight = e.window.data2;
isMinimized = false;
record_error("Window reiszed with proper data");
}
else
{
rWidth = mWidth;
rHeight = mHeight;
record_error("Window resize with improper data");
}
}
WINDOW_WAS_JUST_RESIZED = true;
break;
case SDL_WINDOWEVENT_MINIMIZED:
isMinimized = true;
isResized = true;
mWidth = rWidth;
mHeight = rHeight;
WINDOW_WAS_JUST_RESIZED = true;
record_error("Window minimized");
break;
case SDL_WINDOWEVENT_ENTER:
break;
case SDL_WINDOWEVENT_EXPOSED:
if( isMinimized)
{
isMinimized = false;
WINDOW_WAS_JUST_RESIZED = true;
SDL_SetWindowSize(gpeWindow,mWidth,mHeight);
SCREEN_WIDTH = rWidth = mWidth;
SCREEN_HEIGHT = rHeight = mHeight;
clear_renderer();
record_error("Window unminimized from being exposed!");
}
else
{
record_error("Window exposed!!!!");
}
break;
case SDL_WINDOWEVENT_LEAVE:
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
SDL_SetWindowTitle(gpeWindow,"[Game Pencil Engine]");
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
SDL_SetWindowTitle(gpeWindow,"*Out of Focus*Game Pencil Engine");
break;
case SDL_WINDOWEVENT_CLOSE:
break;
case SDL_WINDOWEVENT_RESTORED:
if( isMinimized)
{
//SDL_SetWindowSize(gpeWindow,mWidth,mHeight);
rWidth = mWidth;
rHeight = mHeight;
isMinimized = false;
record_error("Window restored and unminimized");
}
else
{
rWidth = mWidth = MIN_WINDOW_WIDTH;
rHeight = mHeight = MIN_WINDOW_HEIGHT;
record_error("Window restored.");
}
isResized = true;
WINDOW_WAS_JUST_RESIZED = true;
break;
case SDL_WINDOWEVENT_NONE:
break;
default:
break;
}
}
}
So it appears that the window has to be restored manually at this point(and maximized for normal effect).
Here is what I added in the SDL_WINDOWEVENT_EXPOSED case after checking if the screen was minimized:
I fixed it.
Apparently I have to restore the window.
I added these lines in the expose event (after checking on minimize) and this works:
SDL_RestoreWindow(gpeWindow);
SDL_MaximizeWindow(gpeWindow);
SDL_GetWindowSize(gpeWindow,&mWidth,&mHeight);
I am in the process of making a Snake Game, but I am confused on how to implement the Snake's movement in Processing. I have created a class for the snake, which includes a function for movement that can detect key presses, but I'm stuck on how to actually code the movement of the snake. Can anyone give me a brief explanation on how to implement the Snake movement based on the code below?
int score = 0;
int unit = 20;
PFont courierNew24, courierNew40;
ArrayList unitList;
String direction = "right";
String nextDirection = "";
int directionCount = 0;
class Snake
{
Snake() {
unitList = new ArrayList();
unitList.add(new Unit(4, 3));
unitList.add(new Unit(4, 4));
unitList.add(new Unit(4, 5));
unitList.add(new Unit(4, 6));
unitList.add(new Unit(4, 7));
unitList.add(new Unit(4, 8));
}
void drawSnake()
{
for (int i = 0; i < unitList.size (); i++)
{
Unit snakePiece = (Unit) unitList.get(i);
snakePiece.drawSnakePiece();
}
}
void moveSnake()
{
if (direction != "left" && nextDirection == "right")
{
//Move Snake
}
if (direction != "right" && nextDirection == "left")
{
}
if (direction != "up" && nextDirection == "down")
{
}
if (direction != "down" && nextDirection == "up")
{
}
}
}
class Unit
{
int row, column;
Unit (int unitRow, int unitColumn)
{
row = unitRow;
column = unitColumn;
}
void drawSnakePiece()
{
fill(0, 255, 0);
rect(column*unit, row*unit, unit, unit);
}
void drawApple()
{
fill(255, 0, 0);
ellipse(column*unit+(unit/2), row*unit+(unit/2), unit, unit);
}
void collision(int unitRow, int unitColumn)
{
if (row == unitRow && column == unitColumn)
{
}
}
}
//Functions
void scoreBoard()
{
fill(255);
textFont(courierNew24, 24);
text("Score: " + score, 20, 670);
}
void gameOver()
{
fill(255);
textFont(courierNew40, 40);
textAlign(CENTER, CENTER);
text("Game Over, Score of " + score, 500, 350);
}
void setup()
{
size(1000, 700);
background(0);
courierNew24 = loadFont("CourierNewPSMT-24.vlw");
courierNew40 = loadFont("CourierNewPSMT-40.vlw");
scoreBoard();
}
void draw()
{
smooth();
Snake snake = new Snake();
snake.drawSnake();
snake.moveSnake();
Unit apple = new Unit(10, 10);
apple.drawApple();
}
void keyPressed()
{
switch(key)
{
case 'a':
case 'A':
directionCount += 1;
if (directionCount > 1)
{
direction = nextDirection;
}
nextDirection = "left";
break;
case 'd':
case 'D':
directionCount += 1;
if (directionCount > 1)
{
direction = nextDirection;
}
nextDirection = "right";
break;
case 'w':
case 'W':
directionCount += 1;
if (directionCount > 1)
{
direction = nextDirection;
}
nextDirection = "up";
break;
case 's':
case 'S':
directionCount += 1;
if (directionCount > 1)
{
direction = nextDirection;
}
nextDirection = "down";
break;
}
}
A brief explanation:
You hold all snake units in a list - that's already done. There are head and tail which are the first and the last elements of the list. So it is actually a queue.
On each tick, determine the direction in which you should move. For example, if the direction is left, then next head coordinates will be at (-1,0) relative to current head.
Insert new unit in the list at the head position with the coordinates determined in step 2.
Remove the tail unit from the list (and from the screen).
That will arrange the movement. If you find an apple at the head position, initialize a growth counter. On each tick, if growth_counter > 0, decrease it and skip the tail unit removal. Thus, only head will move until it has grown.
I have added logic to show the Sprite animating but it's simply not showing on the screen. What am I doing wrong?
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
namespace MyXNAGame.Game_Classes
{
public class Player : Sprite
{
private int _frameCount = 6;
private int _frameIndex;
private Rectangle[] _frames;
public float _jumpVelocity = 12f;
public PlayerState _playerState;
public Rectangle BoundingBox
{
get { return new Rectangle {X = (int) Position.X, Y = (int) Position.Y, Height = Texture.Height, Width = Texture.Width}; }
}
public void Initialize()
{
_frames = new Rectangle[_frameCount];
int width = Texture.Width / _frameCount;
for (int i = 0; i < _frameCount; i++)
{
_frames[i] = new Rectangle(i*width, 0, width, Texture.Height);
}
}
public void Load(ContentManager contentManager, string assetName)
{
Texture = contentManager.Load<Texture2D>(assetName);
}
public void Update(GameTime gameTime)
{
while (TouchPanel.IsGestureAvailable)
{
GestureSample gestureSample = TouchPanel.ReadGesture();
if (gestureSample.GestureType == GestureType.Tap)
{
if (_playerState == PlayerState.Running)
{
_playerState = PlayerState.NormalJump;
}
}
if (gestureSample.GestureType == GestureType.Hold)
{
if (_playerState == PlayerState.Running)
{
_playerState = PlayerState.LongJump;
}
}
}
// NormalJump Logic
switch (_playerState)
{
case PlayerState.NormalJump:
Position.Y -= _jumpVelocity;
_jumpVelocity -= 0.5f;
if (_jumpVelocity == 0)
{
_playerState = PlayerState.Falling;
}
break;
case PlayerState.LongJump:
Position.Y -= _jumpVelocity;
_jumpVelocity -= 0.5f;
if (_jumpVelocity == 0)
{
_playerState = PlayerState.Falling;
}
break;
case PlayerState.Falling:
Position.Y += _jumpVelocity;
_jumpVelocity += 0.5f;
break;
case PlayerState.Running:
_frameIndex++;
if (_frameIndex > 5)
{
_frameIndex = 0;
}
break;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, _frames[_frameIndex], Color.White, 0, new Vector2(0, 0), new Vector2(0, 0), SpriteEffects.None, 0);
}
}
}`
Can anyone see the obvious mistake? I am using WP7
I changed the 'Scale' parameter in the Draw() method from new Vector(0,0) to new Vector(1,1) as obviously, having a Scale of 0 will not show anything at all.