How to move a image View left and right in android development - android

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

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
}

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.

Related

how to prevent a user from clicking on a button after another button has been clicked?

I am new to android programming and am building a quiz app in which a question has 4 options and if the user clicks on one of the options the other options should be unclickable. I am currently able to only make a single button unclickable. Here is the java code.
package com.example.android.quiz;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//This method is called when option 1 of question 1 is selected
public void verifyQuestion1Option1(View view) {
Button QuestionOption1 = (Button) findViewById(R.id.question1_option1);
QuestionOption1.setBackgroundColor(getResources().getColor(R.color.solid_red));
question1Answer();
}
public void verifyQuestion1Option2(View view) {
Button Question1Option2 = (Button) findViewById(R.id.question1_option2);
Question1Option2.setBackgroundColor(getResources().getColor(R.color.solid_red));//solid red is not a predefined colour. It is declared in colors.xml
question1Answer();
}
public void verifyQuestion1Option3(View view) {
Button Question1Option3 = (Button) findViewById(R.id.question1_option3);
Question1Option3.setBackgroundColor(getResources().getColor(R.color.solid_green));
question1Answer();
}
public void verifyQuestion1Option4(View view) {
Button Question1Option4 = (Button) findViewById(R.id.question1_option4);
Question1Option4.setBackgroundColor(getResources().getColor(R.color.solid_red));//We call the getResources() method because R.colour.solid_red passed the id of the color not the actual colour value.
question1Answer();
}
public void question1Answer() {
TextView q1Answer = (TextView) findViewById(R.id.question1_answer);
String answer = "Rajinish Kumar is the current Chairman of SBI who took over after Arundhati Bhattacharya retired on 6 October.Shikha Sharma is the Managing Director and CEO of Axis Bank and Chanda Kochhar is the managing director and CEO of ICICI Bank";
q1Answer.setText(answer);
}
}
Either you can use a buttongroup which will have only 1 active button at any point of time or else, you need to disable other button programatically.
To disable the button you can use the following code:
Button button = (Button) findViewById(R.id.button);
button.setEnabled(false);
You can use .setEnabled(false); to disable a button. That button will grey out and does not respond to click events any more.
To disable all buttons, get the handle to each button and set them to disabled.
Button Question1Option1 = (Button) findViewById(R.id.question1_option1);
Button Question1Option2 = (Button) findViewById(R.id.question1_option2);
Button Question1Option3 = (Button) findViewById(R.id.question1_option3);
Button Question1Option4 = (Button) findViewById(R.id.question1_option4);
Question1Option1.setEnabled(false);
Question1Option2.setEnabled(false);
Question1Option3.setEnabled(false);
Question1Option4.setEnabled(false);
That way, all buttons of this question become disabled.
You can also come up with a solution where you save that the button is already pressed and ignore further click events. You could introduce some sort of variable bool question1answered = false; that is set to true as soon as the onClick event is fired.
public void verifyQuestion1Option4(View view) {
if (question1Answered == true) {return;}
question1Answered =true;
//Do the rest of your checks here
}
Two tips for for programming Java:
Java (in contrast to i.e C#) used lower letter variables as convention.
Button question1Option1 = (Button) findViewById(R.id.question1_option1); would be a better way.
If you have more questions, it would make sense to put them in some sort of array and reuse the same four buttons multiple times. That would save you much programming overhead and code rewrites if you have to change something. And it keeps the code cleaner.

Last Button added Dictatorship in android

I know that title is fancy but this is going on in my android app.
I am storing the names of websites which user wants to open in an arraylist of strings. Then an array of buttons is made whose size depends on the size of arraylist.
Then I set the text of the buttons using the arraylist. This works perfectly and all the buttons are assigned correct text.
Then I set the on click listeners of each button and create an implicit intent to open the web site.
Problem that is occuring is that despite the fact the text of the buttons are set perfectly , There is some problem with the listener because no matter which button i press, always the site of last button is opened and hence last button dictatorship.
Here is my code.
package com.example.hp.myproject;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created #CreativeLabsworks
*/
public class Act3 extends Activity
{
LinearLayout ll1; Button[] bt_arr; String s;
LinearLayout.LayoutParams params1;
ArrayList<String> sites;TextView t1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent=getIntent();
sites= intent.getStringArrayListExtra("arraylist");
/*Creating a linear layout to hold editTexts*/
ll1=new LinearLayout(this);
ll1.setOrientation(LinearLayout.VERTICAL);
/*set the width and height of the linear layout*/
params1=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
setContentView(ll1, params1);
/*Initializing the button array*/
bt_arr = new Button[sites.size()];
/*Initialize each button*/
for(int i=0;i<bt_arr.length;++i)
{
bt_arr[i] = new Button(this);
ll1.addView(bt_arr[i]);
}
setText();
attach_listeners();
}
public void attach_listeners()
{
/*this function attaches listeners with all buttons in the button array*/
for(int i=0;i<bt_arr.length;++i)
{
s=sites.get(i);
bt_arr[i].setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+s));
startActivity(i);
}
});
}
}
public void setText()
{
/*This function sets the text of the various buttons*/
int j;
for(int i=0;i<bt_arr.length;++i)
{
j=sites.get(i).indexOf(".com");
bt_arr[i].setText(sites.get(i).substring(4,j));
}
}
}
The problem that you have is that
s=sites.get(i);
S is being set by the last element.
Whenever a button is clicked it is taking the S from the last element since S is outside the onClickListener instance that you have.
I would suggest to save the url in the Button tag and then use it When the button is clicked.
for (int i = 0; i < bt_arr.length; ++i) {
s = sites.get(i);
bt_arr[i].setTag(s);
bt_arr[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String website = (String)v.getTag();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://" + website));
startActivity(i);
}
});
}
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+s));
startActivity(i);
Maybe you do not write i.setclass()?

Do I create separate activities or do I write all the code on one?

I am really new to coding and would like to ask a question. I grabbed some code from mkyongs website and would like to know something. The code has a button that changes an image to a different image. I would like to have 2 buttons that changes the image. First button changes the image to a different image, second button changes that image again. I would like to know if I create a new activity and use all the same code or if I attach the onClickListener again on the same activity. Thanks :)
Here is the code for the button and image change (Activity)
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;
import android.view.View.OnClickListener;
public class MyAndroidAppActivity2 extends Activity {
Button button;
ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
image = (ImageView) findViewById(R.id.imageView1);
button = (Button) findViewById(R.id.btnChangeImage2);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
image.setImageResource(R.drawable.background3);
}
});
}
}
It seems you are trying to Swipe images, the below example is from this site
They created 2 methos (next and previous) on the same activity, that will the images
public void next(View view){
Toast.makeText(getApplicationContext(), "Next Image",
Toast.LENGTH_LONG).show();
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.slide_out_right);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
imageSwitcher.setImageResource(R.drawable.ic_launcher);
}
public void previous(View view){
Toast.makeText(getApplicationContext(), "previous Image",
Toast.LENGTH_LONG).show();
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.slide_out_right);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.slide_in_left);
imageSwitcher.setInAnimation(out);
imageSwitcher.setOutAnimation(in);
imageSwitcher.setImageResource(R.drawable.ic_launcher);
}
However it seems your new to android Development so I recomend to read the basics and try them first , there are hundreds of tutorials on the internet just google. You can start from android site

onClick Listener not working getting no errors

i am having issues getting the coding for onClick to work correctly i have a main activity that contains 8 buttons button 1 should open face book to a page 2,4,5,6 and 7 should open a web browser to defined page and button 8 to open phone dialer with preset number to call. I can not get this to work with out crashing the app i can set one onclick listener to button 1 and get it to work but when i add the next one it crashes the app i get no errors in eclipse i was told to do it with a fragment to handle the onclicks but im lost on how to do this can any one help me with this coding???
This is what i have so far just for 2 buttons still haven't got the one to open face book or the one to open phone dialer but this is as far as i get then it crashes – Jerry 33 mins ago
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addButtonClickListner();
}
public void addButtonClickListner() {
Button btnNavigator = (Button)findViewById(R.id.imageButton2);
btnNavigator.setOnClickListener(new OnClickListener(){
public void onClick(View arg) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("www.*****.com"));
startActivity(intent);
}
});
}
Do this instead
....
package com.example.testcode;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
// Test code: import android.widget.TextView;
// Let your class implement the OnClickListener interface directly. This
// will let you use the onClickListener
class MainActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// "find" our views by their id's in our activity's layout
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
//...... continue for button3 - button8
// set our "click" listeners for each of our buttons
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//...... continue for button3 - button 8
}
// Because our class implements the OnClickListener interface
// it will be listening for "clicks". Because of this, we can
// override the click listener's default onClick(View v) method.
// View v is our view, or our button, that is "clicked".
#Override
public void onClick(View v) {
// Test code: TextView text = (TextView) findViewById(R.id.text);
// This is the statement that will allow each of your buttons
// to perform different processes. For my test code, I have each
// button reset the TextView I have displayed in the top of my
// layout.
switch(v.getId()){
case R.id.button1:
// Test code: text.setText("Button 1");
break;
case R.id.button2:
// Test code: text.setText("Button 2");
break;
//...... continue for button3 - button 8
default:
Log.d(getApplication().getPackageName(), "Button click error!");
break;
}
}
}
Please take a look at my comments. The portion that is commented as
// Test Code:
is code that is pretty much useless for what you are doing. The Test Code from the switch statement is what you need to replace with what you want to do with each individual button. It is also important to note that where I say "//...... continue for button3 - button8" I simply mean to repeat the pattern that I have started with the first two buttons with the remaining six.
If you would like to test it with my given test code, here is my layout (just make sure you erase "// Test Code: " so that the test code lines are no longer commented out:
<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"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press a button"
android:id="#+id/text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
android:id="#+id/button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="#+id/button2" />
</LinearLayout>
NOTES:
It is important to understand that in "good" xml layouts, the "android:text=" portion will be set to 'android:text=#string/"string_id"' instead of some general string to help with localization.
Make sure you change the very top line that declares the package to whatever package you have the Activity placed in. The name of this package is found at "Application"/src/"package_name" and is usually something like com.example.applicationname
I also want to say that I have included the comments in the code so that it can be copied and pasted without having to revisit this link over and over again in case anyone wants to use the code as a guide, not because I wanted tons of code posted in the answer.
Sometime onClick listener doesn't work because of some other
transparent view is on top of your view.

Android Application Crash on button event

I am trying to make a simple android application that can add two numbers, but it is crashing as soon as I press on add button.Please find the code below.The emulator uses 300 MB RAM
I have two editboxes in which numbers are being inputted and their sum is being displayed on third input box by tapping on add button
package example.sample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.close);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
EditText E1=(EditText)findViewById(R.id.editText1);
EditText E2=(EditText)findViewById(R.id.editText2);
EditText E3=(EditText)findViewById(R.id.editText3);
String s=E1.toString();
String m=E2.toString();
// String k="sud";
int num1=Integer.parseInt(s);
int num2=Integer.parseInt(m);
int num3 =num1+num2;
String f=Integer.toString(num3);
E3.setText(f);
}
});
}
#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;
}
change
String s=E1.toString();
String m=E2.toString();
to
String s=E1.getText().toString();
String m=E2.getText().toString();
for getting text from EditText's on Button Click. currently you are trying to parse View's as Integer
String s=E1.getText().toString();
String m=E2.getText().toString();
you are not performing addition operation on numbers. That is why your app is crashing.

Categories

Resources