Two buttons but wrong event is triggered when pushing them - android

I have a very strange behaviour of two buttons:
<Button
android:id="#+id/main_button_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/main_button_measure"
android:layout_centerHorizontal="true"
android:layout_marginTop="76dp"
android:text="#string/button_logout" />
<Button
android:id="#+id/main_button_measure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/main_button_logout"
android:layout_alignStart="#+id/main_button_logout"
android:layout_alignParentTop="true"
android:layout_marginTop="194dp"
android:text="#string/button_measure" />
I initialize them in my main activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.sessionManager = new SessionManager(this);
this.sessionManager.login();
this.setContentView(R.layout.activity_main);
this.buttonMeasure = (Button)this.findViewById(R.id.main_button_measure);
this.buttonMeasure.setOnClickListener(this);
this.buttonLogout = (Button)this.findViewById(R.id.main_button_logout);
this.buttonLogout.setOnClickListener(this);
}
My click listener:
public void onClick(View view) {
switch(view.getId()) {
case R.id.main_button_measure : this.readNFC(view); break;
case R.id.main_button_logout : this.sessionManager.logout(); break;
}
}
Now to the problem: Everytime i push my measure button the logout is called and everytime
i call my logout button the readNFC is called. Whats wrong there?

It happens when you change a layout for example that only part of the application is rebuilt (the rest, e.g. the sources will use the previous build artifacts if they haven't changed) and a resource ID with the same name in the xml layout and the java sources will actually translate to different int IDs.
Try to put a breakpoint in your onCreate() and check the details of the 2 Buttons you set the on click listener of, most likely this.buttonMeasure will reference the logout button
(i.e. will have a top margin of 76dp for example), and vice-versa.
So just clean and rebuild, it should solve your problem.
You can blame it on the build tools ;)

Related

Android radio buttons OnCheckedChangeListener is not working as expected

I added a radio button group to a layout in my project, and on the fragment of this layout I did on this a listener (I use binding). "radioDen" is my radio button group name:
mBinding.radioDen.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
switch(checkedId) {
case R.id.radio_den_circle:
mBinding.setDiameterVisibility(true);
mBinding.setHeightVisibility(false);
mBinding.setWidthVisibility(false);
break;
case R.id.radio_den_none:
mBinding.setDiameterVisibility(false);
mBinding.setHeightVisibility(false);
mBinding.setWidthVisibility(false);
break;
case R.id.radio_den_rectangle:
mBinding.setDiameterVisibility(false);
mBinding.setHeightVisibility(true);
mBinding.setWidthVisibility(true);
break;
}
}
});
But when I choose one of the radio buttons -the project fall, even though that it came to the listener to the right place. When I looked in radio button -android developers , I see that I have to call in the activity to
public void onRadioButtonClicked(View view) {
}
So I just added it like this without any code inside and now it doesn't fall any more, and it keep coming like before to the listener in the fragment.
What is the reason to this problem? Is it a bug of Android? Do you know about another solution? It is just ridiculous to leave it like this...
I checked it now I removed from main activity the function and I do get a fatal error:
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not find method onRadioButtonClicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatRadioButton with id 'radio_den_rectangle'"
#Lakshay you helped me find the answer,
the problem was that in XML I had OnClick reference:
<RadioButton android:id="#+id/radio_den_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/den_circle"
android:onClick="onRadioButtonClicked"
android:padding="5dp"
android:layout_marginEnd="10dp"
android:textSize="18dp"
android:buttonTint="?attr/colorAccent"/>
I just removed it and it works as well !
thanks a lot !!

What could be responsible for an ImageView not being clickable

I am using an ImageView as a NEXT button in my Android app which is responsible for loading the next page of results into the current activity. However, despite that I bind a click listener to it, I cannot seem to capture click events on this ImageView. Here is the XML:
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
android:gravity="left"
android:orientation="horizontal">
<ImageView
android:id="#+id/listBackIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/back_icon"/>
<TextView
android:id="#+id/listBackLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prev"
android:textSize="16dip"/>
</LinearLayout>
And here is the relevant Java code:
ImageView forwardIconView = (ImageView)findViewById(R.id.listBackIcon);
// not sure if necessary; doesn't fix it anyway
forwardIconView.setClickable(true);
forwardIconView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
++pageNumber;
try {
params.put("page", pageNumber);
} catch (JSONException e) {
// do something
}
ConnectionTask task = new ConnectionTask();
task.execute(new String[0]);
}
});
I spent about an hour researching this on Stack Overflow. I found a few places which claimed that ImageView could directly be made clickable, but most things recommended workarounds using other types of widgets.
Does anything about my layout/code stand out as being a culprit for this behavior?
Update:
I also tried binding a click listener to the TextView at the same level as the ImageView and this too failed to capture clicks. So now I am suspecting that the views are being masked by something. Perhaps something is capturing the clicks instead of the views.
I would set it up like this:
private ImageView nextButton;
nextButton = (ImageView)view.findViewById(R.id.back_button);
Util.loadImage(getActivity(),R.drawable.some_image,nextButton); //Here i would load the image, but i see you do it in XML.
nextButton.setOnClickListener(nextButtonListener);
nextButton.setEnabled(true);
View.OnClickListener nextButtonListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v(TAG, "ImageView has been clicked. do something.");
}
};
This works for me.
Why not use android:drawableLeft attribute for the textview instead of using imageView​ and textview both in a linearlayout .
<ImageView
android:id="#+id/listBackIcon"
...
android:clickable="true"
Or you can try overriding onTouchListener with ACTION_DOWN event filter, not onClickListener. Also check for parrents with android:clickable="false", they could block childs for click events.
What seemed to work for me was the accepted answer from this SO question, which suggests adding the following the every child element of the LinearLayout which I pasted in my question:
android:duplicateParentState="true"
I don't know exactly what was happening, but it appears the click events were not making it down to the TextView and ImageView. Strangely, the click events were reaching a Button, when I added one for debugging purposes. If someone has more insight into what actually happened, leave a comment and this answer can be updated.

Add Event Handler to ImageButton

I am developing an Android app that has an ImageButton in it, and I need to add an event handler to it. In my attempt to do this, I have added a new function to the .java file that Android Studio creates when you make new project that looks like this:
public void tapImageButton(ImageButton myImgBtn) {
// Code that does stuff will come later on.
}
After doing this, trying to set the onClick proerty does not show the function, and trying to enter it manually causes the app to crash when I test it.
You must have View as a parameter of method that you wish to call, while bind click event through layout file.
Try this:
public void tapImageButton(View view) {
// Code that does stuff will come later on.
Toast.makeText(this, "clicked !!", Toast.LENGTH_SHORT).show();
}
In xml:
...
android:onClick="tapImageButton"
...
I am not very familiar with android studio but when i tried making a button and having it do something on click i first added the android:onClick = "some_method_name" to the XML that makes the design of the app. I first added the name in the onClick and then i clicked on the name. When the little light bulb icon shows up the arrow next to it give the option of creating a method with that method name that you just wrote. once you create it then you add the code of whatever you want to happen when you click. Hope it works.
For Example, This is the XML:
<Button
android:id="#+id/playButton"
android:text="#string/play"
android:textSize="25sp"
android:background="#0099FF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:onClick="startGame" />
This is the Java:
public void startGame(View view) {
Intent intent = new Intent(this,GameActivity.class);
startActivity(intent);
}

Find and return the ID of the current view

I'm trying to set up a "close to start" button in a game. The game takes the user from view to view like a maze. The user could be on any view, but I want a way to get them back to the start screen. Is there a way to find and return the ID of the current view for my findViewByID? I've found a I've tried the following code in various forms:
OnClickListener closetomain = new OnClickListener() {
#Override
public void onClick(View v) {
int currentid = v.findFocus().getId();
RelativeLayout hideme = (RelativeLayout)findViewById(currentid);
hideme.setVisibility(View.GONE);
setContentView(R.layout.main);
// RelativeLayout showme = (RelativeLayout)findViewById(R.id.startLayout);
// showme.setVisibility(View.VISIBLE);
}
};
Okay, it turns out I should have given each close button the same ID and used theisenp's suggestion for the simplest code (well, that I could understand). It also turns out that I should have started by putting each level/layout in its own activity. You live and you learn I guess. Below is my XML and java. It may not be the elegant solution but I'm not sure I care all that much as long as it works.
<ImageButton android:id="#+id/closeButton"
android:layout_height="wrap_content"
android:background="#drawable/close"
android:layout_width="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:onClick="closetomain">
</ImageButton>
And here's my Java:
public void closetomain(View view) {
switch(view.getId()) {
case R.id.closeButton:
setContentView(R.layout.main);
break;
}
}
Why do you need to retrieve the id of the current view? Is it just so that you can set it's visibility to GONE? If so, there are probably better ways of implementing that same functionality.
Instead of just changing the layout with setContentView(), it would probably be a better idea to have the Start Screen be its own separate activity. When you are in any of the "maze views" you could simply use an intent to start your home screen activity like this
Intent startScreenIntent = new Intent(this, StartScreen.Class);
startActivity(startScreenIntent);
Then you won't have to worry about finding id's or changing visibilities, plus the code is cleaner, because it separates the code for your Maze levels and your Start Menu.

Extremely Simple Menu Question for Android

I have a very simple question about menu control in Android. I'm writing a program that performs some simple numeric calculations and outputs an answer. My question is how do make the program move to second screen when a button is pressed, and how can I let the user move back to the original screen.
Here's a quick example
Screen 1
"Add Numbers"
Input 1st # ____
Input 2nd # ____
(Add)
Screen 2
The answer is "____"
The user inputs two integers. presses add, and then the program moves to the second screen which displays the answer. If they user wants they can return to the first screen and start over.
I know this has been covered but with so many resources I don't know what to look for. Answers or links to resources would be most helpful. Thank you!
You can use the following layout for the screen to input numbers. Name the file first.xml.
<TextView
android:id="#+id/firstnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input Ist:"
android:textSize="20px"
android:textStyle="bold"
/>
<EditText
android:id="#+id/first"
android:layout_height="wrap_content"
android:layout_width="250px"
/>
<TextView
android:id="#+id/secondnumber"
android:text = "Input 2nd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20px"
android:textStyle="bold"
/>
<EditText
android:id="#+id/second"
android:layout_height="wrap_content"
android:layout_width="250px"
/>
<Button
android:id="#+id/add_button"
android:text="Add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15px"
android:layout_centerHorizontal="true"
/>
</LinearLayout>
To add these numbers
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(this);
EditText num1 = (EditText)findViewById(R.id.first);
EditText num2 = (EditText)findViewById(R.id.second);
}
The click listener code
public void onClick(View v) {
int n1 = Integer.parseInt(num1.getText().toString());
int n2 = Integer.parseInt(num2.getText().toString());
int result = n1 + n2;
String res = Integer.toString(result);
Intent intent = new Intent(getApplicationContext(), Result.class);
intent.putExtra("result", result); //Passing the result to the second activity using intent
startActivity(intent);
}
In the Result.java class.
public class Result extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Intent intent = getIntent();
String result = intent.getStringExtra("result");
TextView t1 = (TextView)findViewById(R.id.result);
t1.setText(result);
}
}
Hope this helps..
May I know what type of language are u using?
I recently just did it with C#.
My flow is that, when I start a program, it will auto be forced to the second screen, with some power options.
But if yours is just moving the program the diff screens, it will be easy in C#.
Screen Srn = Screen.PrimaryScreen; // gives your information of Primary Screen.
Screen[] Srn = Screen.AllScreens; //gives u an array of all your available screen( srn[0] is primary screen, etc)
So, using the intellisense from the IDE, should be able to get the width, height, etc.
Cant remember exactly, but something like src.width or src.bounds.width.
Easiest way to move your program will be to move the program x axis to the respective screen.
ViewFlipper will work well. You could also try "startActivityForResult" to pass your answers to the next screen.
Take a look at the ViewFlipper class. It works like tabs, but without the tabs UI. You can use an xml layout to display your 2 (or more) screens, and showNext() or showPrevious() to flip between the screens.

Categories

Resources