I've already tried searching the Google on how to switch activities in android studio, even in the official documentation with tutorial. I did it exactly like it was said but I am still unable to get redirected to another activity after clicking a button.
I've entered an onClick name of the method to the button
it looks like this: https://i.imgur.com/pmsztaL.png (can't post images yet)
and this is my MainActivity.class file with said method
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void handleButtonAddNew(View view) {
MainActivity.this.startActivity(new Intent(MainActivity.this, AddItemActivity.class));
}
}
After pressing the button in a phone, the button does nothing.
This is my AddItemActivity.class
public class AddItemActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
}
public void handleButtonRemember(View view) {
finish();
}
}
How come the button doesn't work, what did I do wrong?
EDITS
EDIT: Successfully ran emulator and the buttons did in fact work, the problem lies within my phone, the buttons there don't want to work. Where could be the issue now?
EDIT: XML Layout of MainActivity.class
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".MainActivity">
<Button
android:id="#+id/buttonAddNew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="188dp"
android:layout_marginRight="188dp"
android:layout_marginBottom="264dp"
android:text="#string/buttonAdd"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="395dp"
android:layout_height="715dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</android.support.constraint.ConstraintLayout>
EDIT: The problem was with scroll view blocking the clickable button so on my phone the button didn't register any clicks, after removing the scrollview the button works normally.
I'm afraid that this button doesn't get any listeners attached.
The programatic approach
From the Official Android Documentation
I'd suggest you use this in your onCreate callback:
Button button = (Button) findViewById(R.id.your_btn_id);
button.setOnClickListener((view) -> { theMethodYouWantToCallHere(view); });
XML approach
Please double check the following using this approach
Your activity is registered in the AndroidManifest.xml
You're including the android namespace to the XML file in the parent container of the layout file. IE: xmlns:android="http://schemas.android.com/apk/res/android"
Make sure you're setting the content view for the activity with setContentView(R.layout.your_layout_file);
Once 2 is satisfied make sure you're using the android namespace. IE: android:onClick="yourMethod"
As you're currently doing: Make sure the onClick callbacked method has the View view parameter; no more, no less
Make sure the onClick function is public in the activity.
And that no other clickable views are covering the view you're registering the onClick listener for :)
Including the namespace: xmlns:android="http://schemas.android.com/apk/res/android"
XML file
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:text="Click me!" android:onClick="clicked" android:layout_height="wrap_content" android:layout_width="wrap_content"/>
</FrameLayout>
The activity
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void clicked(View view){
Toast.makeText(this, "Hey! Im clicked!",Toast.LENGTH_SHORT).show();
}
}
Related
The following code is trivial but simulates the problem.
activity_main.xml
<?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=".MainActivity">
<Button
android:id="#+id/btnGoToExtra"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="266dp"
android:text="Go To Extra"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
layout_extra.xml
<?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">
<Button
android:id="#+id/btnBackToMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="186dp"
android:text="Back To Main"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnGoToExtra)
.setOnClickListener(v -> {
setContentView(R.layout.layout_extra);
findViewById(R.id.btnBackToMain)
.setOnClickListener(vv -> {
setContentView(R.layout.activity_main);
});
});
}
}
Question
I can navigate to the layout_extra from activity_main and return to activity_main. Unfortunately, after this round trip, I can no longer be able to navigate to layout_extra anymore.
What causes this problem and how to fix it?
Explanation will follow in chat but that is not how it is supposed to be done, For views to change, You have other options like using Fragments or using new activity entirely, I would also like to suggest moving to kotlin.
public class MainActivity extends AppCompatActivity {
View mainView;
View extraView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainView = getLayoutInflater().inflate(R.layout.activity_main, null);
extraView = getLayoutInflater().inflate(R.layout.layout_extra, null);
setContentView(mainView);
mainView.findViewById(R.id.btnGoToExtra)
.setOnClickListener(v -> {
setContentView(extraView);
});
extraView.findViewById(R.id.btnBackToMain)
.setOnClickListener(vv -> {
setContentView(mainView);
});
}
}
Reading through the snippet above, here's how everything went
The line
findViewById(R.id.btnGoToExtra)
.setOnClickListener
Registers Button with id btnGoToExtra for click events and when that happens you have the nested
findViewById(R.id.btnBackToMain)
.setOnClickListener
Which registers the element with id backToMain for click events and that's all
Calling setContentView() multiple times is not recommended. The normal way to switch between layouts in the same activity is to use a ViewFlipper or FrameLayout
From here
You then have:
XML
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:src="#drawable/icon"
android:scaleType="fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
<TextView
android:text="Learn-Android.com"
android:textSize="24sp"
android:textColor="#000000"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
code
private void SwitchLayout2() {
RelativeLayout Layout1 = (RelativeLayout)findViewById(R.id.layout1);
RelativeLayout Layout2 = (RelativeLayout)findViewById(R.id.layout2);
// Enable Layout 2 and Disable Layout 1
Layout1 .setVisibility(View.GONE);
Layout2.setVisibility(View.VISIBLE);
}
private void SwitchLayout1() {
RelativeLayout Layout1 = (RelativeLayout)findViewById(R.id.layout1);
RelativeLayout Layout2 = (RelativeLayout)findViewById(R.id.layout2);
// Enable Layout 1 & Disable Layout2
Layout1.setVisibility(View.VISIBLE);
Layout2.setVisibility(View.GONE);
}
I am developing a small project of test, and I wrote the following code.
I already created in the xml file, a button with id called "registerBtn".
I erased the imports of this source code to shorten space of this source code.
In the java file, I created a variable called mRegisterBtn, in the type of Button.
Inside the method called onCreate(Bundle savedInstanceState) the mRegisterBtn receives the method called findViewById(R.id.registerBtn);
However, in the mRegisterBtn.setOnClickListener, the part of new View.OnClickListener appears in gray color, and it is not working when trying to test this code.
This image shows what I really mean. Please, perceive that the the part of new View.OnClickListener appears in gray color. It means a error. But trying to compile, this code runs, but the button simply does not work.
Can anyone know how to fix this error, please?
public class Register2 extends AppCompatActivity {
Button mRegisterBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register2);
mRegisterBtn = findViewById(R.id.registerBtn);
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Testing", Toast.LENGTH_LONG).show();
}
});
}
}```
<?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"
android:background="#007FFF"
tools:context=".Register">
<Button
android:id="#+id/registerBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/white"
android:text="Register"
android:textColor="#color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try using the Activity itself as the Context.
If you want a log, then make one
If you want the gray to go away, use a lambda
Log.d("REGISTER", "Setting listener");
mRegisterBtn.setOnClickListener(view -> {
Log.d("REGISTER", "Clicked!");
Toast.makeText(Register2.this, "Testing", Toast.LENGTH_LONG).show();
});
I started learning android, I'm trying to make a login activity but my buttons doesn't work for any reason.
I have implemented view.OnClickListener in my class
Here's my java code :
public class Login extends AppCompatActivity implements View.OnClickListener{
private Button btn_login, btn_reset;
private EditText et_username, et_pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.bt_login_login);
btn_login.setOnClickListener(this);
btn_reset = (Button) findViewById(R.id.bt_log_reset);
btn_reset.setOnClickListener(this);
et_username = (EditText) findViewById(R.id.et_log_username);
et_pwd = (EditText) findViewById(R.id.et_log_password);
}
#Override
public void onClick(View v) {
Log.w("test","test");
switch(v.getId()){
case R.id.bt_login_login :
DisplayData();
break;
case R.id.bt_log_reset :
resetData();
break;
}
}
I was wondering if this was not caused by the fact that my buttons are in a tree like this :
activity_login.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".Login">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/txt_username"/>
<EditText
android:id="#+id/et_log_username"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/txt_login"/>
<EditText
android:id="#+id/et_log_password"
android:layout_width="match_parent"
android:inputType="textPassword"
android:hint="#string/pwd"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal|center_vertical"
>
<Button
android:id="#+id/bt_login_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/intro_login"/>
<Button
android:id="#+id/bt_log_reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/reset"/>
</LinearLayout>
</LinearLayout>
Ps : I may have a bad english, sorry for the inconvenience
make sure that your activity implements View.OnClickListener
everything else seems fine.
You can try a different approch. You can pass an anonymous class implementation of OnClickListener when using setOnClickListener.
Another way to do it is define an onClick attribute in the xml for each button, give it a functions name. You will have to have a function with the exact name in the activity for the function to be triggered (Android Studio will not let the project compile without a proper connection between them.)
The anonymous class implementation is prefered, as you will not be able to declare events in the xml all the time (when using fragments for example).
to implement an anonymous class in the setOnclickListener do this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//stuff to do when the button was clicked goes here.
}
});
so for a school project I'm making an app, but I"m stuck.
I've got a button on my main class.
XML code of this class:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.example.larsb.csvvg.Home"
android:background="#drawable/home">
<Button
android:id="#+id/Lariks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button"
android:visibility="visible" />
<Button
android:id="#+id/Salland"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="45dp"
android:text="Button"
android:visibility="visible"
android:layout_alignTop="#+id/Lariks"
android:layout_alignLeft="#+id/Lariks"
android:layout_alignStart="#+id/Lariks" />
<Button
android:id="#+id/CSG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:visibility="visible"
android:layout_below="#+id/Salland"
android:layout_alignLeft="#+id/Salland"
android:layout_alignStart="#+id/Salland" />
</RelativeLayout>
So what I want to do is when I button click Lariks I switch to a new activity.
I try to do this with the following code:
public class MainActivity extends AppCompatActivity {
private static int WELCOME=4000;
Button lariks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lariks = (Button)findViewById(R.id.Lariks);
lariks.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent=new Intent(MainActivity.this,Home.class );
startActivity(intent);
finish();
}
},WELCOME);
}
}
In the public void onClick(view) thing I got the code for switching activity, that's not the problem.
The problem is that as soon as I add the:
lariks.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
the app can't launch anymore. It starts the emulator but it keeps saying the app has stopped. Anyone has any idea why this is? If I remove that part of the code the app actually does run.
Your Button with android:id="#+id/Lariks" is not in the activity_main layout (as evidenced by tools:context="com.example.larsb.csvvg.Home" and your crash). Therefore findViewById(R.id.Lariks) returns null, and attempting to call setOnClickListener() on this null reference causes a crash.
Your findViewById()-setOnClickListener() pair should likely be in the Home activity, or the button should be in the activity_main layout.
I am doing the first experiment with Android and I have the following problem with this simple application.
Basically my application consist into an ImageView showing a background immage, a TextView showing a message and a button.
When the user click this button the text of my TextView have to change and the background immage of my *ImageView also have to change.
So this is my activiy_main.xml file containing the layout of my main activity:
<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:background="#B388FF"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="#+id/android_cookie_image_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="centerCrop"
android:src="#drawable/before_cookie" />
<TextView
android:id="#+id/status_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
android:text="I'm so hungry"
android:textColor="#android:color/white"
android:textSize="34sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="EAT COOKIE"
android:onClick="eatCookie"/>
</LinearLayout>
And this is the code of the previous activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void eatCookie(View v) {
TextView messaggio = (TextView) findViewById(R.id.status_text_view);
messaggio.setText("I'm so full");
ImageView sfondo = (ImageView) findViewById(R.id.android_cookie_image_view);
sfondo.setImageDrawable(Drawable.createFromPath("#drawable/after_cookie"));
}
}
As you can see, when the user click the button it is perform the eatCookie() method that first retrieve the TextView reference and change the text of this TextView. It works fine.
Then it retrieve the reference related to the ImageView and try to change the viewed immage, I have done it by this line:
sfondo.setImageDrawable(Drawable.createFromPath("#drawable/after_cookie"));
In my project I have put the after_cookie.jpg file into the /res/drawable/ folder.
The problem is that it can't work. The default immage of the android_cookie_image_view disappear but is not replaced with the after_cookie.jpg image.
What is wrong? What am I missing? How can I fix this issue?
Try this
sfondo.setImageDrawable(getResources().getDrawable(R.drawable.after_cookie));
Use this instead.
ImageView sfondo = (ImageView) findViewById(R.id.android_cookie_image_view);
sfondo.setImageDrawable(getResources().getDrawable(R.drawable.after_cookie));
And make sure you call that eatCookie function on onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eatCookie();
}