The button of a Android project simply does not work [duplicate] - java

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();
});

Related

Same button (with action) on multiple layouts

I'm making an android app and i want to put a settings button on every layout in the app. When i press the settings button, a custom dialog pops up and i can access the app settings.
The problem i'm having is that i want to refer to 1 method in some class (doesn't matter to me which one). I'm already using the include in my XML of my layouts like this:
<include android:id="#+id/settingsButton"
layout="#layout/settingsbuttonlayout"/>
The settingsbuttonlayout.xml file looks like this:
<?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="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/root_vg">
<ImageButton
android:layout_width="50dp"
android:layout_height="50dp" app:srcCompat="#drawable/settingsicon"
android:id="#+id/settings_dialog"
android:cropToPadding="true"
android:adjustViewBounds="false" android:scaleType="fitCenter"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintHorizontal_bias="0.133"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintVertical_bias="0.123"
android:clickable="true"
android:focusable="true"
android:background="#drawable/customdialog" android:onClick= "showSettings"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
You can see that there is an onclick defined in this layout. However (for as far as i know) this means i need the same "showSettings" method in every layout class. How can i work around this so i should only write the "showSettings" method once and can refer to it?
This is the showSettings method:
public void showSettings(View v){
Dialog dialog = new Dialog(this, R.style.DialogStyle);
dialog.setContentView(R.layout.settings_dialog);
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialogbackground);
Button btnClose = dialog.findViewById(R.id.close_settings);
btnClose.setOnClickListener(view -> dialog.dismiss());
dialog.show();}
PS: I'm pretty new into making apps and GUI's. I didn't learn it yet in school and i'm just figuring out everything myself so sorry if this is some straightforward or stupid question :)
you can remove the onClick attribute from your setttings_dialog which calls the showSettings, next create a Utility.java file in which you can make your function as static
public static void showSettings(View v){
Dialog dialog = new Dialog(this, R.style.DialogStyle);
dialog.setContentView(R.layout.settings_dialog);
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialogbackground);
Button btnClose = dialog.findViewById(R.id.close_settings);
btnClose.setOnClickListener(view -> dialog.dismiss());
dialog.show();}
now in whichever class you want to call this method just write
Button settingsButton = (Button) findViewById(R.id.settingsButton);
settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Utility.showSettings(v);
}
});
After searching some more I found the following:
From whichever class i wanted to open the dialog i have to write this:
SettingsDialog.showSettings(this);
In my SettingsDialog class i have the following:
public class SettingsDialog {
static void showSettings(Context context) {
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.settings_dialog);
Dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialogbackground);
}
dialog.show();}
}

Add an ImageView statically in Android Studio

I want to change the resource of an image view from a variable in android studio.
Let me explain you, i have first activity "selector activity" which has 21 images, on every image click, a variable god_name is changed to the particular god, now i am sending that variable using putExtra, now i want that to change the resource of an ImageView in MainActivity depending on the variable, for example if the variable is "two", then i want to change the resource to "R.drawable.two".
Something like that, I have some experience in python so I used f strings there, here can I do something?
MainActivity.class
(Note-I have not Included imports so the code is allowed to be uploaded.)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String god_name = getIntent().getExtras().getString("chosen_god").toString();
ImageView god = findViewById(R.id.god);
god.setImageResource();
}
}
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"
android:background="#color/black"
tools:context=".MainActivity">
<ImageView
android:id="#+id/god"
android:layout_width="413dp"
android:layout_height="496dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.666"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#mipmap/hanuman" />
</androidx.constraintlayout.widget.ConstraintLayout>
I can use multiple if conditions and switch case statement but that would be so much large as I would have to write it 21 times so it is very difficult!
Thanks in advance for anyone kind of help!
That sounds like you need to use the resources.getIdentifier() to make this work.
I wrote once an answer to a related topic: https://stackoverflow.com/a/4865350/180538
Anyway what you need is to pass the name of the resource and then resolve the identifier to use it. So something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// make sure that god_name is the name of the resource, so AFTER R.mipmap.[resourceName]
// so for R.mipmap.two you need to pass "two" as "chosen_god" extra
String god_name = getIntent().getExtras().getString("chosen_god").toString();
ImageView god = findViewById(R.id.god);
int resId = getResources().getIdentifier(god_name, "mipmap", getPackageName());
god.setImageResource(resId);
}

How to create two android button using android studio

I am just getting into android apps, and I have yet to find a tutorial that explains in detail of how to do anything.Can someone show me the code on how to create two buttons (sign in and sign up) in android ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginButton=(Button)findViewById(R.id.button);
button.setOnClickListener(LogInListener);
signUpButton=(Button)findViewById(R.id.button2);
button2.setOnClickListener(SignUpListener);
}
private OnClickListener LogInListener=new OnClickListener()
{
public void onClick(View v)
{
}
}
Is this the correct way to implement? thanks
activity_main.xml
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:id="#+id/button"
android:layout_marginTop="61dp"
android:layout_below="#+id/textView3"
android:layout_toStartOf="#+id/button2"
android:layout_toLeftOf="#+id/button2" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign UP"
android:id="#+id/button2"
android:layout_alignTop="#+id/button"
android:layout_alignLeft="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp" />
EDIT:
Now that you have edited your question, you just need to do one more thing to declare your Buttons as instance variables. Declare them outside of all methods (onCreate) but inside the mainActivity.
PRE EDIT:
I'll show you what your main activity (Java class) and what your layout (XML file) should look like:
Main Activity:
public class MainActivity extends AppCompatActivity {
Button signIn, signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = (Button) findViewById(R.id.'idOfButtonFromXMLLayout');
signUp = (Button) findViewById(R.id.'idOfButtonFromXMLLayout');
//Looking at my XML code, the signIn id would be R.id.signInButton
}
The findViewById method is inherited from the AppCompatActivity class, all activities extend the AppCompatActivity class. Older versions of android just extended the Activity class.
The findViewById method takes an int parameter more specifically an id.
The reason a cast is required is because the findViewById method as you would assume returns a type of View, this is then casted to a button.
XML Layout File:
<RelativeLayout
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:padding="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/signInButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign In"
<!-- Complete Layout Details--> />
<Button
android:id="#+id/signUpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/signUpText"
<!-- Complete Layout Details--> />
</RelativeLayout>
In the code above I have represented the text of the buttons in two ways...
1) Hard-coded string "Sign In"
2) String resource "#string/signUpText
It is good practice to change your hard-coded strings to the latter format.
If you're new at Android Development some things are just confusing. I would create buttons by doing this:
Define Button in your XML File.
Add Listener to your Button.
Don't forget to add id attribute to your Button.
i would do it this way.
LAYOUT XML FILE
<Button
android:id="#+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button One" />
<Button
android:id="#+id/buttonTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.onClickListener {
private Button buttonOne;
private Button buttonTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOne = (Button) findViewById(R.id.buttonOne); // id located in your xml file
buttonOne.setOnClickListener(this);
buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setOnCliclListener(this);
}
private void onClick(View v){
switch(v.getId()) {
case r.id.buttonOne: {
// action when buttonOne is clicked
break;
}
case r.id.buttonTwo: {
// action when buttonTwo is clicked
break;
}
}
}
To create a button, you have to code in your xml file, or drag it in your Design view which will do that for you
Which will auto-magicly do this for you, with auto generated values.
-to name your button edit android: text
-edit android: id to edit the "key" that connects your button design in xml to java
If you want to use your button for things like onclicklisteners and such, you will need to "import" it into your java code, like so. The android: id ="#/<>value"and findViewById(R.id.) should be the same (though its not in the photos)
Now simply do this again for every button you want and change the values to your needs. Hope I helped.

setOnClickListener never fired - Android/Eclipse

I'm having a problem that seems to be quite common but none of the solutions on here so far have helped me.
I am trying to add a simple button to my app which will start a new activity when clicked.
The button displays ok in my app but when I touch it nothing happens.
My problem is that setOnClickListener() is never fired - when I debug it just skips right over it and no logging message is displayed in LogCat.
Here is my layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="sarah.tourapplication.MainActivity"
tools:ignore="MergeRootFrame" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
<RelativeLayout
android:id="#+id/belowlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<Button
android:id="#+id/cam_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Take Picture" />
</RelativeLayout>
And this is my activity:
public class MainActivity extends FragmentActivity implements OnClickListener {
Button camButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent locationUpdatesIntent = new Intent(this, GetLocationUpdates.class);
startActivity(locationUpdatesIntent);
camButton = (Button)findViewById(R.id.cam_button);
//add button functionality
camButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TEST", "Button was clicked.");
Intent cameraIntent = new Intent(getApplicationContext(), CameraActivity.class);
startActivity(cameraIntent);
}
});
}
Can anyone tell me where I've gone wrong? I'd really appreciate any pointers.
I'm using Eclipse on Windows 8 and everything I'm using is up to date.
Thanks in advance!
Thanks for all the help. It turns out that I was calling the click handler in the wrong activity.
Try removing the lines
Intent locationUpdatesIntent = new Intent(this, GetLocationUpdates.class);
startActivity(locationUpdatesIntent);
It looks like you're starting a different activity before you actually get to the point where you're adding the listener...
Sorry I'm on my phone but try to use setOnClickListener(this); and override the onClick method. Inside the onClick method use if (view == yourview) to do w/e you want. :). If it still doesn't work try removing the startActivity method at the very beginning of your codes

Cannot Change Layout Content In Java Code

Very simple question but very weird as well :
I have a class PanelGlobalActivity that extends Activity and it is set to the layout panel_view_activity. I have a button and a text view, both have IDs.
When I do findViewById(R.id.*) it can see my button and my text view but there is no way I can change their values or anything. Like button.setText("Hello") would compile but wouldn't change it.
Any ideas ?
Here is my xml file (panel_view_activity):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And here is my java class :
public class PanelGlobalActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.panel_view_activity);
TextView label = (TextView)findViewById(R.id.text1);
label.setText("Test");
}
}
Thanks.
Nic.
You can try something like this:
public class PanelGlobalActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button someButton = (Button) findViewById(R.id.yourButtonId);
someButton.setText("text changed");
}
}
some tips in coding if your using eclipse:
1.Use Ctrl + Shift + O (Imports necessary libraries or whatsoever automatically)
2.Use Ctrl + W (this lists all the possible methods for an object) just like when you're typing the "someButton.s" then press Ctrl + W, all available methods will be showed
You don't have any problem on your sample code ... I've run it it's perfectly fine . ..

Categories

Resources