How to initialize a view in an Android Method? - java

I am working on an Android Application that will take the height and weight of a person and calculates its BMI and Required calories based on Gender and Age.
When I press calculate button, the onClick method should be activated and thus there is another method called in the implementation of the 1st method.
The problem is that they are asking me to initialize the view and I dont know what do they mean and how to initialize in this case.
here's my java code for this:
public void calculateCalories()//this is the onClick method
{
View view;
onRadioButtonClicked(view); // here I get the error
}
public void onRadioButtonClicked(View view)
{
boolean checked=((RadioButton) view).isChecked();
switch (view.getId())
{
case R.id.male:
if (checked)
male_calories();
break;
case R.id.female:
if (checked)
female_calories();
break;
}
}

If I understand correctly your Java code doesn't know which of your activity views is your checkbox, that's why you are getting an error.
The common practice to initialise a view is writing this line in onCreate method:
CheckBox cb = (CheckBox) findViewById(R.id.yourcheckboxname);
Then to add listener:
cb.addOnCheckChanged(this);
and implement onCheckChanged within your Java class.
And you don't need to manually call onCheckChanged() - it's fired automatically everytime user checks or unchecks the checkbox

Related

One OnClick handler for multiple buttons in a fragment

I have 3 buttons in a fragment that I want to use the same click event. How can this be achieved within a fragment?
XML
<Button
android:id="#+id/btn_1"
android:onClick="btnClick_DoSomething"
android:text="#string/one"/>
<Button
android:id="#+id/btn_2"
android:onClick="btnClick_DoSomething"
android:text="#string/two"/>
<Button
android:id="#+id/btn_3"
android:onClick="btnClick_DoSomething"
android:text="#string/three"/>
Java
#Override
public void btnClick_DoSomething(View v) {
}
Error
#Override (within the fragment Java class) becomes underlined in red and the following error is returned
Annontations are not allowed here
I want the onClick event to be the same for all 3 buttons
You dont need to write #Override annotation as you are not overriding the method. Just use
public void btnClick_DoSomething(View v) {
}
You will get a callback in this method at runtime.
you simply don't do it in XML, do it in Java instead:
<Button
android:id="#+id/btn_1"
android:text="#string/one"/>
<Button
android:id="#+id/btn_2"
android:text="#string/two"/>
<Button
android:id="#+id/btn_3"
android:text="#string/three"/>
then...
private final OnClickListener onClick = new OnClickListener(){
#Override
public void onClick(View view){
switch(view.getId()){
... cases...
}
}
somewhere initialising the views you do:
fragmentView.findViewById(R.id.btn_1).setOnClickListener(onClick);
fragmentView.findViewById(R.id.btn_2).setOnClickListener(onClick);
fragmentView.findViewById(R.id.btn_3).setOnClickListener(onClick);
}
What method are you trying to override? Do any of the parent classes have a method btnClick_DoSomething? You do not need to override anything when setting a click listener from a Layout XML. Just ensure that a method of the same name with a void return type and a View as its only argument exists in the activity class that will use this layout
The general way to distinguish clicks from different Views in the same onClick handler is to identify them by id
public void btnClick_DoSomething(View v){
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
There are some misunderstandings here. To override a Click event, your Fragment need to implement the View.OnClickListener interface like this:
public class YourFragment extends Fragment implements View.OnClickListener{
#Override
public void onClick(View v) {
}
}
Note that the name of the method must be onCLick, must return void and recives a View as a parameter to be overrided from the interface. In this case you need to set a Listener to each button in your fragment:
btn1 = (Button) view.findViewById(R.id.btn_1);
btn1.setOnClickListener(this);
Inside this method you can control which object was clicked by it´s ID
#Override
public void onClick(View v) {
int id = v.getId();
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
Or, you don't need to override the method, so remove the anotation that will work's fine :
public void btnClick_DoSomething(View v) {
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
Instead of declaring the onClick method in the xml layout file, you could have your Fragment implement View.onClickListener interface, override onClick(), and set all 3 buttons onClickListener like this btn.setOnClickListener(this). Put the behavior you want for all 3 buttons in onClick(). All 3 will have the same behavior (unless you check which button the event came from in onClick()).

What does the onclick listener (this) mean?

btn_Login.setOnClickListener(this);
In android studio.
I've seen this in countless places. What does this mean? I know how this operates but what is the listener called then?
This example is from: Link
Suppose that you have 16 Buttons and every button has setOnclicklistener this means that you are creating many repetitions of similar code to this in your class. And that makes your code ugly, also this is not the efficient way to write your code. So to make your code efficient you have to implement OnClickListener() on your activity and then for each button use buttonX.setOnClickListener(this). Now use the override onClick method. In this method, you can use either the switch case block or if-else to identify which button is pressed. So in the onClick method you just have to give ids of the button.
Implement OnClickListener in Activity
public class MyActivity extends Activity implements View.OnClickListener {
}
For each button use this:
buttonX.setOnClickListener(this);
After this implement override the onClick method
#Override
public void onClick(View view) {
switch(view.getId){
case R.id.buttonX:
// Do something
break;
}
in that example its defined like this
private Button btn_Login;
Button is a class
onClickListener is a listener, to set the listener he is using setOnClickListener method.
From the next time if u need to those kind of clarifications don't post in a separate thread, add a comment in that question itself.
Thank You #august alsina
It is a listener that helps to specify the events to occur on click of a widget.
When your class implement View.OnClickListener, you can defined your click of each button in method public void onClick(View v). Keyword this refer to the method onclick. It is good to use this way when there are a lot of button in your class file. You can define following code On Create method:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
and define its definition oncreate method. For example:
public void onClick(View v){
int id= v.getId();
switch (id){
case R.id.btn1: {
//do sth
//break;
}
case R.id.btn2: {
//do sth
//break;
}
...
}
}
In layman's terms
By writing btn_Login.setOnClickListener(this);
whenever btn_login will be pressed program will go to onclick method public void onClick(View v)
and then you can write in the method what you want to do when button is pressed

Trying to call a method from 1st class activity and keep the same argument in a 2nd class activity (android studio)

Currently finishing up an app I have been working on but I'm kinda stuck on this last thing.
The app has 2 activities, one with buttons that are categories and the other shows the information according to the button pressed. For example if you click the button Fast food, it goes to the 2nd screen and displays info on that.
I'm trying to get a refresh button on the 2nd activity that will call a method in the 1st activity to refresh new information depending on the button pressed. The problem is that I don't know how to make it so the method keeps the same argument when called. What I mean is, if fast food was clicked, the refresh button would get new info that still relates to the fast food category.
Here's the relevant code in the Main activity:
public void yelpSearch(View view) {
switch (view.getId()) {
case R.id.button: buttoncategory = "Restaurant";
break;
case R.id.button2: buttoncategory = "Chinese restaurant";
break;
case R.id.button3: buttoncategory = "Fast Food";
break;
and this on the 2nd Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
Refresh();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void Refresh() {
MainActivity mActivity = new MainActivity();
mActivity.yelpSearch();
}
I'm not sure what to put inside mActivity.yelpSearch();
I tried using (View view) but it'll say cannot resolve symbol view. And if I make a local variable for view, it'll say not initialized and I don't know what to set it as
Any help would be awesome, been googling on this for a while now and searched through tons of questions on here as well. I'm still new at this so bear with me
I think you want to pass data between activities?
First Activity(Send DATA):
String data="YourXXXdata"
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("DATANAME", data);
startActivity(intent)
second Activity(Receive DATA):
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("DATANAME");
}
The data now is in String value
*you have to put in data the value you need depend you preview select button.
Make your yelpSearch method static
and call it like this from 2nd activity MainActivity.yelpSearch();

How to make the switch work?

There is a lot programmatically created buttons, that's 2 of them:
Button agafon_1 = new Button(this);agafon_1.setText(R.string.txt_agafon_1);llPreViewList.addView(agafon_1, lParams);
Button agafon_2 = new Button(this);agafon_2.setText(R.string.txt_agafon_2);llPreViewList.addView(agafon_2, lParams);
There OnClickListener and it has a switch. What do I need to insert in place of the question marks to make the switch work?
switch (???) {
case ???:
//
break;
case ???:
//
break;
}
The file R.java not even mention the id buttons which makes it impossible to use v.getId()...
If you are using the same OnClickListener for every Button set a different id for every Button with Button.setId(int) and the use v.getId() for your switch, where v is the argument of onClick(). Otherwise you can create a different OnClickListener for every button
You class should implement OnClickListener
public class MainActivity extends Activity implements OnClickListener
Then
Button agafon_1 = new Button(this)
agafon_1.setId(yourbuttonid);
agafon_1.setOnClickListener(this);
Then
#Override
public void onClick(View v)
{
switch(v.getId())
{
case buttonid1 : // id must match
break;
case buttonid2 :
break;
...
}
}

Change if any EditText is in focus

In my program i use many EditText dynamically created , and i need to call method each time when any of them get changed (lost focus). is it possible to do such thing ?
otherwise how to make on focus lost\change lister for all View ?
you will need to set View.setOnFocusChangeListener for EditText to listen for focus change .
For Example:
View.OnFocusChangeListener editTextFocusChnage=
new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
swich(v.getId()){
case Edittext1_id:
// do your work here..
break;
case Edittext2_id:
// do your work here..
break;
case Edittext3_id:
// do your work here..
break;
.....
}
}
};
where Edittext1_id,Edittext2_id,.... is dynamic EditText id's
EDIT :-
add FocusChangeListener to EditText's as:
editText1.setOnFocusChangeListener(editTextFocusChnage);
editText2.setOnFocusChangeListener(editTextFocusChnage);
editText3.setOnFocusChangeListener(editTextFocusChnage);
.....

Categories