Reputation: 135
I am very new to Android Development, and I am trying to develop a game. In this game, I will require a Imageview to move left and right when pressed by a button. My current IDE that I am using is "Android Studio". So I have done research but am not finding any answers. My current code is
package com.example.turtle;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
Button left, right ;
ImageView turtle ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
left = (Button) findViewById(R.id.bl);
right = (Button) findViewById(R.id.br);
turtle = (ImageView) findViewById(R.id.IVT);
left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
So yeah, As you can see I set up an OnClcikListener but I don't know what goes under it. I heard I can lessen a position, but how would I do that ? Like what is the code to lessen a position ? Thanks
Upvotes: 0
Views: 8373
Reputation: 562
At least for the newer Android studio this is how I would do it.
In your xml text code,(in your design/layout page go on the bottom and click text)
<Button
android:onClick="LeftBonClick"
(plus any additional xml code you have for this button.)
/>
And then on you java code...
public void LeftBonClick(View view) {
turtle.setX(turtle.getX() - 2); //<<code depending on your preference and what layout your turtle is in.
//add any code you want to happen here, when the left button is clicked
}
Upvotes: 2
Reputation: 4081
You can set the new parameteres for your ImageView with the following code inside onClick() method:
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(50,50, 0,0);
// OR
params.topMargin= 50;
turtle.setLayoutParams(params);
Hope that will help you.
Upvotes: 0