How to Implement a method inside Activity class - java

I'm just starting to learn Android programming with Android Studio and unfortunately, but I have a big problem with probably a very simple thing, namely in the layout file of the main activity, I assigned the startActivity() method to the android:onClick property of the both buttons (android:onClick="startActivity()").
And now I should in the MainActivity class, implement startActivity() method but.... I do not know how to do it.
I saw that I should have in MainActivity: public void startActivity(View v). I tried and I was looking for solutions for a few hours and I already lost hope.
Especially that I can implement e.g. View.OnClickListener but methods, startActivity() can not do anymore. How could I implement this method?
I assigned the startActivity() method to the android:onClick property of the both buttons in activity_main.xml:
<Button
android:id="#+id/button"
android:onClick="startActivity()"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
android:text="#string/button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="OnClick" />
<Button
android:id="#+id/button2"
android:onClick="startActivity()"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="16dp"
android:text="#string/button2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button"
tools:ignore="OnClick" />
Next i should in the MainActivity class, implement startActivity() method but.... I do not know how to do it :
public class MainActivity extends AppCompatActivity implements startActivity() {
Button b1, b2;
EditText et1, et2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.button);
b2 = findViewById(R.id.button2);
et1 = findViewById(R.id.editText);
et2 = findViewById(R.id.editText2);
public void startActivity(View v) {
if (v.getId() == R.id.button) {
String name = et1.getText().toString();
int age = Integer.parseInt(et2.getText().toString());
Intent i = new Intent(this, ResultActivity.class);
i.putExtra("name", name);
i.putExtra("age", age);
startActivity(i);
} else {
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.pl/"));
startActivity(i); }
}
}

You're incorrectly using onClick attribute. This is wrong:
android:onClick="startActivity()"
it should be:
android:onClick="startActivity"
Read more at https://developer.android.com/guide/topics/ui/controls/button#HandlingEvents
Suggestion
You should avoid using android:onClick in your xml. Use the onClickListener instead. It's important to separate your logic and UI layout so you don't need to think too much whenever your xml layout is changed. Use something like this:
Button button = (Button) findViewById(R.id.your_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something here when button is clicked.
}
});

As mentioned by ישו אוהב אותך9A
https://developer.android.com/guide/topics/ui/controls/button#HandlingEvents
Responding to Click Events
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
//onClick function/method name don't use round brackets
android:onClick="sendMessage" />
and in your activity
//JAVA
/** Called when the user touches the button */
public void sendMessage(View view) {
// Do something in response to button click
}
//Kotlin
/** Called when the user touches the button */
fun sendMessage(view: View) {
// Do something in response to button click
}
and remove the tools:ignore="OnClick"
i hope it helps

Firstly, change this
android:onClick="startActivity()"
to this:
android:onClick="startActivity"
Then move your startActivity method below OnCreate method. It is currently inside OnCreate

Related

Android Studio My Button on the second Activity doesn't Work

I think it a very easy Question. I am new to Android Studio and I could not find an answer.
I have an activity that switches per Button to another activity. However, on my second activity, my simple Button just to change the Textview which doesn't work.
Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".StartActivity">
<TextView
android:id="#+id/twText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="127dp"
android:layout_marginLeft="127dp"
android:layout_marginTop="88dp"
android:layout_marginEnd="127dp"
android:layout_marginRight="127dp"
android:layout_marginBottom="624dp"
android:text="Ihr Passwort war Richtig!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnChecke"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="134dp"
android:layout_marginLeft="134dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="189dp"
android:layout_marginRight="189dp"
android:layout_marginBottom="371dp"
android:text="Check"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
onCreate method in my second activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tw = findViewById(R.id.twText);
btnCheck = findViewById(R.id.btnChecke);
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText("work");
}
});
}
And this is how I am starting the second activity (onCreate method from my first activity).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tw = findViewById(R.id.twText);
Button btnCheck = findViewById(R.id.btnChecke);
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView("Work"R.layout.activity_main);
}
});
}
I have checked the variable names in the layout and looks like everything is fine.
Thank you in advance.
This answer is based on the problem which I found before the latest edit from the OP. Here is the version of the edit where I found the problem.
First of all, something is very wrong about the onClickListener of your button. You are setting the content view again, instead of starting your second activity. It looks like, you are just setting the content view of your StartActivity which actually does not launch the MainActivity that you are trying to start.
In order to start a new activity, you need to add the following in your button onClickListener.
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// setContentView(R.layout.activity_main); // This is not the way for starting another activity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
});
Once your MainActivity has started, you should be able to change the text with no problem.
Bundle bundle = getIntent().getExtras()
if(bundle.getString("changeTextView")
TextView .... = (TextView) ....setText();
Hi. If I good understand, you should use Intent with "putExtra()".
Exmple:intent.putExtras("changeTextView");
After that in your onCreate() method you can put:

Multiple activity on one button click

I have a problem with creating 2 activities for 1 button. I created a button and I managed to connect that button with one activity but I dont know how to add another activity to the same button.. What am I trying to do is that when we press on that button it will start playing animation (I managed to do that) but I also want it to send SMS to a specific number. I have code for that, but I dont know how to include / connect everything together.
Code from a button:
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent" />
Code from a imageview (animation):
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:scaleType="centerInside"
android:src="#drawable/keers" />
Code from main activity, for animation:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);
running = false;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(!running){
((AnimationDrawable) imageView.getDrawable()).start();
running = true;}
}
}
);
}
}
Now what I want to add for the same button is this :
public void sendText(View paramView)
{
Toast.makeText(this, "SENT",Toast.LENGTH_SHORT).show();
SmsManager.getDefault().sendTextMessage("+3564245237",null,"1", null, null);
I'm not that experienced in programming, so it might be pretty easy for you guys.
Both actions seen to be fired by the same Button, so you may add both to the onClickListener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(!running){
((AnimationDrawable) imageView.getDrawable()).start();
running = true;}
Toast.makeText(view.getContext(), "SENT",Toast.LENGTH_SHORT).show(); //Or YourActivity.this
SmsManager.getDefault().sendTextMessage("+3564245237",null,"1", null, null);
}
}

Android start new activity when clicking widget

I am new with coding Java and xml for android applications and I wanted to know how I start/open a new activity when clicking on something. In this case I am using a relative layout to keep a image and text together as one object. What I want to do is when you click on it it will start/open the new activity. How do I do this? Could someone tell me step by step since I am quite new to this.
First of all, if you want your layout to act (RelativeLayout) like a button (do not handle onClick on layout child components) firstly set in your xml layout file RelativeLayout attribute
android:clickable="true"
Or you can do this directly in your code (in onCreate method)
relativeLayout.setClickable(true);
Than you need to set onClickListener for your layout.
You can do this simply by creating anonymous class
relativeLayout.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent startActivityIntent = new Intent(getApplicationContext(),YourDesiredActivity.class);
startActivity(startActivityIntent);
}
}
UPDATE
Layout is defined in xml file, of course in Android you can do this in code ,but it is better to use xml file.
In your IDEA you have folder res->layout here you should place your layout files. For example layout with name `
relative_root_layout.xml
<xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative_layout"
android:layout_height="wrap_content" android:layout_width="wrap_content">
<ImageView
android:id="#+id/image_view">
android:layout_width="wrap_content"
android:src="#drawable/icon"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
ImageView>
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_toRightOf="#+id/image_view"
android:text="Relative layout">
TextView>
RelativeLayout>
But in case you have only text and image it is better to use
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#android:drawable/btn_image"
android:text="Button with Image"
android:gravity="left"
android:drawablePadding="10dp">
Button>
How you can access your widgets ?
This is very basic thing you have to know if you are developing for android, this is essential part. Please read documentation, read books, watch tutorial or whatever.
In short you need to inflate layout in activity onCreate() method
RelativeLayout mRelativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.relative_root_layout);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);
mRelativeLayout.setOnClickListener(.....)
}
But again this very basic things you must know.
You could set onClickListener for any of your views.
ImageView image = (ImageView) findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Youractivity.this, Moveactivity.class));
}
});
Starting a new activity is done by creating an Intent and then calling startActivity, e.g.
Intent intent = new Intent(context, AnotherActivity.class);
context.startActivity(intent);
You can wrap this code in an OnClickListener as other answerers already suggested.
A second option is to add an android:onClick attribute to your RelativeLayout
<RelativeLayout ...
android:onClick="clickMe">
<ImageView .../>
<TextView .../>
</RelativeLayout>
and in your activity
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void clickMe(View notused) {
Intent intent = new Intent(this, AnotherActivity.class);
this.startActivity(intent);
}
}
See startactivity for a complete example.

How do i create a button to another page for my app

i was just wondering how i would make a button on my page so that it would go to another page for my app. I am a beginner so if you could explain how it all works and where it goes it would help a lot.
PS i am using android studio if that makes a difference and this is the code i have so far in my fragment_main.xml. I have not entered any code into the .java
<TextView android:text="#string/hello_world"
android:id="#id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/firstbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/homebutton"
android:layout_below="#+id/text"/>
You can declare views and objects dynamically in Java, and then pass the button from fragment to fragment (or Activity to Activity, depending on your app).
To declare a Relative Layout with a Button, for example:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.RelativeLayout;
public class JavaLayoutActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button myButton = new Button(this);
RelativeLayout myLayout = new RelativeLayout(this);
myLayout.addView(myButton);
setContentView(myLayout);
}
This doesn't set the properties or anything, I am just using this as proof of concept.
XML makes things easy with regards to user interface design because you don't have to manage it in code, but this is one case where it is an exception. If you want dynamic interface objects, you need to use Java.
Instead of creating view dynamically you should obtain your view in activity
ImageButton button = (ImageButton) findViewById(R.id.firstButton)
and assign an onClick listener to id
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// start new Activity here
}
});
You can also do it in xml:
<ImageButton
android:id="#+id/firstbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/homebutton"
android:onClick="sendMessage"
android:layout_below="#+id/text"/>
with such configuration, you should add method in activity:
public void sendMessage(View view) {
// start another activity here
}
There are two methods available in android using which you can go from one Activity to another.
1. Use button.setOnClickListener()
Create a button in xml file.
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
Now set event listener for the button in your .class file
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the event you want to perform when button is clicked
//you can go to another activity in your app by creating Intent
Intent intent = new Intent(getApplicationContext, Activity2.class);
startActivity(intent);
}
});
2. Use <android:onClick="goNext">
Put the onClick as the attribute of the button you have created in xml file.
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="goNext" />
Now in your .class file define an event for that button as,
goNext() {
Intent intent = new Intent(getApplicationContext, Activity2.class);
startActivity(intent);
}

How i can compare the value of an id with java

I have a simple xml with a question and two buttons. When one of buttons is pushed i will compare if the id of the pushed button is equal to "Blanco" or "Negro".
The XML code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/pregunta" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Blanco"
android:onClick="respuesta"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Negro"
android:onClick="respuesta"/>
</LinearLayout>
</LinearLayout>
This is de java code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void respuesta(){
//The doubt.
//Here the if/else to compare ID with the button text
}
}
Don't do it like that. Create an onClickListener for each Button, so you know exactly which one is being pressed. For example:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener{
public void onClick(View v) {
// call code here, knowing that button1 was pressed
}
});
button2.setOnClickListener(new View.OnClickListener{
public void onClick(View v) {
// call code here, knowing that button2 was pressed
}
});
}
}
implement onClickListener into your Activity.
public class MainActivity extends ActionBarActivity implements OnClickListener
Declare the Button variables inside your class
Button btblanco, btnegro;
Implement the clickListener event on onCreate
btblanco = (Button) findViewById(R.id.button1);
btnegro = (Button) findViewById(R.id.button2);
btblanco.setOnClickListener(this);
btnegro.setOnClickListener(this);
And put this inside onClickListener method.
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
Toast.makeText(getApplicationContext(), "Blanco", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "Negro", Toast.LENGTH_SHORT).show();
break;
}}
if you are interested in just knowing which button was clicked, then add a onclicklistener to the button objects. Google for it a bit and the samples you find will show you how to use a switch case structure to d actions based on which button was clicked.

Categories