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.
Related
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 have designed a simple Android Application to test how setOnFocusChangeListener works.
The Java Code:
public class MainActivity extends AppCompatActivity {
TextView tv;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.textView);
et = findViewById(R.id.edittext);
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
if (b) {
tv.setText("Edit Text is focused!!");
}
else {
tv.setText("You stopped focussing on editText");
}
}
});
}
}
The XML Code:
<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"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Nothing happened"
android:textSize="30sp"
android:gravity="center"
android:id="#+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Write here!!!"
android:id="#+id/edittext" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Me!!" />
</LinearLayout>
But when I click on the edit text to write something, Edit Text is focused!! and displayed on the text view.
After stopping the focus, the EditText is never displayed on screen, even when I click anywhere else on the screen or on a button. I would like to know when the else part of onFocusChange will be displayed?
I guess it is cause the editText is never leaving the focus.
On the GUI editor or XML, there is a property named "focusOnTouch" which editText Views have on true by default that let you get the focus for the editText, but if there is no other view with that property on true too, no view could get the focus.
That property exists for every View, set it to true for each View you want to consider to get the focus when clicking, otherwise, the focus won't be passed to other views like your textView or button.
I have a couple of buttons I want to make a computation on, so I want to get the ID of the particular button clicked so I can perform an operation on.
I have configured the id for all my buttons in my XML file.
I hope i can get help here.
<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"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="15dp"
android:textSize="45dp"
android:gravity="center_horizontal"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/displayCalc"
android:text="0"></TextView>
<Button
android:id="#+id/button_one"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="1"
android:onClick="one"/>
<Button
android:id="#+id/button_two"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="2"
android:onClick="two"/>
<Button
android:id="#+id/button_three"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="3"
android:onClick="three"/>
<Button
android:id="#+id/button_add"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="+"
android:textColor="#color/design_default_color_primary_dark"
android:textSize="18sp"
android:onClick="calcAdd"/>
</LinearLayout>
Your question is a little strange. If I got it correctly you want to know which button is clicked in Java/Kotlin and perform some operation based on buuton id.
If that is what you want:
Implement View.OnClickListener in your activity or fragment related to this xml.
Implement onCLick(View) method.
Now you can use when (kotlin) or switch (java) to find the clicked button id.
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button_one.setOnClickListener(this)
button_two.setOnClickListener(this)
}
override fun onClick(v: View) {
when (v.id) {
R.id.button_one -> {
//TODO (do something for button with id button_one)
}
R.id.button_two -> {
//TODO (do something for button with id button_two)
}
}
}
}
You have defined in the XML file for the Button with id button_one with this attribute:
android:onClick="one"
that the listener will be a method named one, so all you have to do is create that method inside your activity like this:
public void one(View view) {
<your code goes here>
}
If you want to refer to the Button inside that method you can do it like this:
Button button = (Button) view;
and if you want its id:
int id = button.getId();
So create 4 methods (like the one above) inside your Activity class for all 4 buttons: one(), two(), three() and calcAdd().
say you're doing something like that
Button buttonOne = findViewById(R.id.button_one); //now you have access to the button that is in your layout
buttonOne.setOnClickLister(new View.OnClickListener(){ // i hope you understand anonymous inner class
#Override
public void onClick(View v){ //now when your button is clicked this method is called
//and you passed v in argument which is nothing but your button
//you're passed a View object and not a out of the box button because the
//View.OnClickListener can be implemented on any view if you want to call button
//specific method on it you cast it to a button , because you know it is a button
//inside
v.getId() //gives you the id of your button which you wanted
}
}
Tell me there is still some confusion .
I am new to Android Studio, and I'm following this tutorial to learn how to code. I put a button into my activity_main.xml and referenced the onClick property of the button to the method buttonOnClick in my MainActivity.java file using the drag-and-drop method (Design tab of the xml file). The original code is as follows:
activity_main.xml (non-relevant code omitted):
<Button
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="visible"
android:onClick="buttonOnClick (MainActivity)" />
MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonOnClick(View v) {
Button button = (Button) v;
button.setText("Click");
}
After I ran this code, when I clicked the button, it crashed. If I removed the (MainActivity) part of the onClick property, it worked. I have no idea why this worked, but it did. Would someone perhaps be able to tell me why?
The error message I received when the app crashed is as follows:
java.lang.IllegalStateException: Could not find method buttonOnClick
(MainActivity)(View) in a parent or ancestor Context for
android:onClick attribute defined on view class
android.support.v7.widget.AppCompatButton with id 'button'
It appears that (View) is assumed so you do not need to ask for (MainActivity) as well.
<Button
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="visible"
android:onClick="buttonOnClick" />
Change the android:onClick="buttonOnClick (MainActivity)" to
android:onClick="buttonOnClick"
Try this:
remove android:onClick="buttonOnClick (MainActivity)" from xml
<Button
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="visible" />
write the onClick in code
public class MainActivity extends AppCompatActivity {
public Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
b1.setText("Click");
}
});
}
}
I am having an issue with a click listener for a login modal submit button.
This is the error.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I have a reasonable understanding of what a null pointer exception is and I have search thoroughly for an issue similar to mine. I have tried to reformat the click listener in several ways, made sure I have the correct view ID etc.
package...
import...
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
//Variables
String currentPage = "";
Stack<String> crumbs = new Stack<String>();
//Fragment managing the behaviors, interactions and presentation of the navigation drawer.
private NavigationDrawerFragment mNavigationDrawerFragment;
// Used to store the last screen title. For use in {#link #restoreActionBar()}.
public CharSequence mTitle;
//temp
AuthenticateUserTokenResult authenticateUserTokenResult;
String loginErrorMessage = "";
String loginErrorTitle = "";
Boolean logonSuccessful = false;
Dialog loginDialog;
// Login EditTexts
EditText Username;
EditText CompanyID;
EditText Password;
Button Submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle(); // Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
if(authenticateUserTokenResult == null) {
attemptLogin();
}
}
public void attemptLogin() {
loginDialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
loginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
loginDialog.setContentView(R.layout.login_modal);
loginDialog.setCancelable(false);
//loginDialog.setOnCancelListener(cancelListener);
loginDialog.show();
Submit = (Button)findViewById(R.id.Submit);
Submit.setOnClickListener(new View.OnClickListener() // the error is on this line (specifically the .setOnClickListener)
{
#Override
public void onClick(View v)
{
ClyxUserLogin user = new ClyxUserLogin();
Username = (EditText)findViewById(R.id.Username);
user.logon = Username.getText().toString();
CompanyID = (EditText)findViewById(R.id.CompanyID);
user.idCompany = Integer.parseInt(CompanyID.getText().toString());
Password = (EditText)findViewById(R.id.Password);
user.password = Password.getText().toString();
user.idApplication = 142;
authenticate(user);
}
});
}
There is more, obviously, but not relevant to the topic I think.
Here is the XML file for the dialog that has the button on it.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#3366FF">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#FFFFFF" >
<TextView
android:id="#+id/LoginTitle"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:textColor="#000000"
android:textSize="20sp"
android:text="Login" />
<EditText
android:id="#+id/Username"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/LoginTitle"
android:layout_margin="10dp"
android:hint="Username" />
<EditText
android:id="#+id/CompanyID"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/Username"
android:layout_alignStart="#+id/Username"
android:inputType="number"
android:hint="Company ID" />
<EditText
android:id="#+id/Password"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/CompanyID"
android:layout_alignStart="#+id/Username"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="#+id/Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Password"
android:layout_marginBottom="10dp"
android:layout_centerHorizontal="true"
android:text="Login" />
</RelativeLayout>
</RelativeLayout>
Any help would be greatly appreciated.
Submit is null because it is not part of activity_main.xml
When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.
try this instead :
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Another thing : you use
android:layout_below="#+id/LoginTitle"
but what you want is probably
android:layout_below="#id/LoginTitle"
See this question about the difference between #id and #+id.
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
Because Submit button is inside login_modal so you need to use loginDialog view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Try giving your Button in your main.xml a more descriptive name such as:
<Button
android:id="#+id/buttonXYZ"
(use lowercase in your xml files, at least, the first letter)
And then in your MainActivity class, declare it as:
Button buttonXYZ;
In your onCreate(Bundle savedInstanceState) method, define it as:
buttonXYZ = (Button) findViewById(R.id.buttonXYZ);
Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.
Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);
I too got similar error when i misplaced the code
text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
I got it working on placing the code in right order as shown below
setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});