I am doing the simplest of onClick models and cannot get the onClick method to fire. I know it is something simple, and I am new to Android. Any help is appreciated.
package com.bordeloniphone.timeentry;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class TimeEntryActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
Button okButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
okButton = (Button) findViewById(R.id.btnOK);
okButton.setText(":)");
okButton.setOnClickListener(this);
//setContentView(okButton);
}
public void onClick(View v) {
Log.d("TEST", "TEST");
Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show();
}
}
Here is the main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnOK"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
After much angst and gnashing of teeth, I figured it out. I had to delete the emulator device and add an new one and now it works like a champ. I appreciate everyone trying to help.
Instead of setting the onClicklistener to this, try this approach:
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("TEST", "TEST");
Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show();
}
});
You should try Cleaning your project or try to restart your Eclipse or any other Editor you are using as it is a valid code and should work fine.
UPDATE:
Also, you should check your Logcat, are you getting the output of Log.d("TEST", "TEST"); because your Toast seems to be implemented in a wrong manner.
Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show(); // wrong
Toast.makeText(Activity_name.this, "TEST", Toast.LENGTH_SHORT).show(); // correct
Using this in Toast inside the Listener means you are Referencing the Listener, which indeed should not be the case. You have to reference to the Activity itself so better use Activity_name.this.
Button iv_StyleInspiration_Back = (Button) findViewById(R.id.iv_StyleInspiration_Back);
iv_StyleInspiration_Back.setOnClickListener(this);
Try this Whenever you implement onclick in your activity you need to set as above to make it work for all controls and onclick should look something as below
#Override
public void onClick(View pView) {
if (null != pView) {
switch (pView.getId()) {
case R.id.iv_StyleInspiration_Back:
//do what you want
break;
default:
break;
}
}
}
Check for Three Steps:
find the button by id correctly
link the button to a listener. (adding the actionListener)
you specify a condition for this button in case of implementing an actionListener class.
try making the button clickable
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnOK"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="OK"
android:clickable="true" />
Related
I'm new to Android app.. I was trying to change the button color on first click and to change back to default on the next click and this will work no matter how many times user clicks...
Can anyone help me to understand this
Create global variable clickStatus
boolean clickStatus=true;
final Button running_app=(Button)findViewById(R.id.running_app);
running_app.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clickStatus){
clickStatus=false;
running_app.setBackgroundColor(Color.parseColor("#3F51B5"));
}else {
clickStatus=true;
running_app.setBackgroundResource(android.R.drawable.btn_default);
}
}
});
Simple, Just give two different tags to button and keep toggling it on button click. That would help you to change background colour alternatively. Here is the complete code for it. Hope this helps.
Here is main.xml
<?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/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Click Me" />
</LinearLayout>
Here is MainActivity.java
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(this);
btnClick.setTag("1");
btnClick.setBackgroundColor(Color.BLUE);
}
#Override
public void onClick(View view) {
if (view.getTag().equals("1")) {
view.setTag("0");
btnClick.setBackgroundColor(Color.RED);
} else {
view.setTag("1");
btnClick.setBackgroundColor(Color.BLUE);
}
}
}
this my xml file main
<?xml version="1.0" encoding="utf-8"?>
<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:background="#raw/christmas"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/by_kostas"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="83dp"
android:text="#string/by_kostas"
android:textSize="20sp"
android:textColor="#F2F3F4"/>
<ImageView
android:id="#+id/settings"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="nameOfMethod"
android:src="#raw/settings" />
</RelativeLayout>
and my java Main
package com.kostas.mytorch;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//start our layout
super.onCreate(savedInstanceState);
setContentView(R.layout.main);{
final ImageView diskView = (ImageView) findViewById(R.id.settings);
diskView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//my codes
}
});
diskView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// System.out.println("image clicked...");//in my logcat
startActivity(new Intent("com.kostas.standroid.settings"));
}
});
}
}
my problem is when i click in the settings icon, my program crashes instead of what i wanted to create a new layout (settings xml is just black page),can someone be kind enough to help me out
You can attach click listener to any view by two ways:
In xml, write onClick attribute of the view and pass the method
name you have implemented in the activity.
Example: android:onClick="someMethod" and in the activity code, declare a method
public void someMethod(View view)
{
// handle click here
}
In activity, use setOnClickListener() to the view.
For now, try this:
diskView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// System.out.println("image clicked...");//in my logcat
startActivity(new Intent(Main.this, settings.class));
}
});
Also remove this line from xml: android:onClick="nameOfMethod"
Some time there is contextual problem. Try this.
Intent intent = new Intent(CurrentActivity.this, UpcomingActivity.class);
startActivity(intent);
Also don't forget to define class in Manifest file
try to remove
android:onClick="nameOfMethod"
from the xml layout. I believe this is the method that it's called when you click the settings button and it doesn't exist so it crashes.
Ok this may seem like a pointless example but if I can figure this out then the program I am trying to make will work. So I have two activities test and test two each with one button.
Test 1:
package thompson.cameron.com;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View button = findViewById(R.id.testButton);
button.setOnClickListener(this);
}
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
}
and test2
package thompson.cameron.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test2 extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
View test = findViewById(R.id.testButton);
test.setOnClickListener(this);
}
public void onClick(View v){
switch (v.getId()){
case R.id.testButton:
System.exit(1);
}
}
}
When I click the button on Test it is supposed to launch test2 however it is at this point I get an null pointer exception that I have narrowed down to test.setOnClickListener(this); line of code. Below are my two xml files for the layout. I can get the button to work when I only have one activity but as soon as I add a second activity with a different layout file it all falls apart
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST TEST TEST"/>
</LinearLayout>
main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST2 TEST2 TEST2"/>
</LinearLayout>
I'm still new at Android programming so thanks for all your help.
Open the Debug perspective in Eclipse
Choose the 'Breakpoints' view tab.
Select the 'Add Java Exception Breakpoint' and choose
NullPointerException.
Launch your activity, either by using 'Debug As...' or attaching
the debugger to a running instance via DDMS.
Execute the offending workflow. It will break on the line that
caused the NullPointerException.
In your test.java file give:
implements View.OnClickListener
Initialize your button as:
Button testButton = (Button) findViewById(R.id.testButton);
and inside your onClick method, check whether you are clicking button:
if(v == testButton) {
//give ur intent code
}
There are different ways to perform onClick functionality.
One is the above method which I have mentioned.
Another one is what ankit has mentioned.
Third way is through your layout.
Inside your layout for your button tag, you may give as:
<Button android:id="#+id/testButton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Click" android:onClick="onTestButtonClick" />
And inside your class just mention the below details for button:
public void onTestButtonClick(View view) {
//give your intent code
}
You may refer to the link also:
http://android-developers.blogspot.com/2009/10/ui-framework-changes-in-android-16.html
Make sure that both activities are register at the application's manifest file.
As a side note never call System.exit in your code. You can call finish() to close an Activity and this will bring at the front the previous Activity on the stack.
The issue here is that you haven't typecasted your views to buttons.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; // Needed to add this import for the button casting below
public class Test extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// I have changed View to Button and then typecasted
// with the "(Button)" the return of findViewById
Button button = (Button) findViewById(R.id.testButton);
button.setOnClickListener(this);
}
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
}
Let me know if you have any issues with this. I just completed my first experiment through using the onClickListener implementation through the main class instead of individual anonymous listeners.
Andrew
I had the same problem, you may put the same content view that the button,
setContentView(R.layout.main); if the button is in that content view, in other case, you will put:
setContentView(R.layout.buttoncontentview);
View button = findViewById(R.id.testButton);
button.setOnClickListener(this);
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
setContentView(R.layout.main);
sorry for my bad english, but i'm spanish
Implement OnClickListener interface
and set button.setOnClickListener(this);
and override
public void onClick(View v) {
}
I think your buttons IDs need to be different in different activities. R.id.testButton would refer to only one button.
The final solution is that you may modify the AndroidManifest.xml file, i finally solved my error in this link How to register a new activity in AndroidManifest.xml?
You can try this.it may work.
package thompson.cameron.com;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test extends Activity{
private Button button;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = findViewById(R.id.testButton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i=new Intent().setClass(Test.this,Test2.class);
startActivity(i);
}
});
}
}
First of all in main.xml and main2.xml chage the button's ids like in below code.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST TEST TEST"/>
</LinearLayout>
main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/testButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST2 TEST2 TEST2"/>
</LinearLayout>
It throws nullpointerexception because of id confict with each other so in your java file use following code to find button.
In Activity 1
Button button = findViewById(R.id.testButton);
button.setOnClickListener(this);
and
In Activity 2
Button button = findViewById(R.id.testButton1);
button.setOnClickListener(this);
I start a new activity when clicking on a button , but the content(ui components) of the new activity doesn't appear , why ??
button listener to start new activity
m_sendButton.setOnClickListener(
new OnClickListener(){
public void onClick(View view) {
Intent in = new Intent(context, SendMessageForm.class);
// i.putExtra("id","4");
context.startActivity(in);
//Toast toast = Toast.makeText(context, "Error. Please try again later", Toast.LENGTH_SHORT);
//toast.show();
} }
);
SendMessageForm.java
import android.app.Activity;
import android.os.Bundle;
public class SendMessageForm extends Activity {
public void onCreat(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_result_form);
}
}
search_result_form.xml (just for test)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Send" android:id="#+id/btnBacksds"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
You have a typo in your onCreate method. The method name says onCreat - it's missing an 'e':
import android.app.Activity;
import android.os.Bundle;
public class SendMessageForm extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_result_form);
}
}
In general it's useful to use the #Override annotation to help you catch any mistakes such as this. If the parent class does not have a matching method signature then your IDE (at least Eclipse does this) will warn you or present an error.
I'm trying to get a simple onClick to fire from an ImageButton - it seems like a simple enough task, but I'm obviously missing something here.
Here is my java file:
package com.jlbeard.android.testapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class testapp extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//handle the button press
ImageButton mainButton = (ImageButton) findViewById(R.id.mainButton);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//show message
Toast.makeText(testapp.this, "Button Pressed", Toast.LENGTH_LONG);
}
});
}
}
Here is my layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/whereToEat"
android:src="#drawable/where_to_eat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="8px"
/>
<ImageButton
android:id="#+id/mainButton"
android:src="#drawable/main_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#null"
android:clickable="true"
android:onClick="mainButtonClick"
/>
</RelativeLayout>
It seems to me that I'm missing something simple... but can't seem to figure it out. Thanks!
You didn't run show() method on Toast object. Very common mistake :-)
You also might have a problem due to the manifest setting onClick
android:onClick="mainButtonClick"
If mainButtonClick exists on post 1.5 devices it may be called instead, overriding the one you're setting in code
In my case, the imageButton was displayed behind a list. Because the list was empty, the ImageButton was seen but onClick was never fired.
Adding android:elevation="5dp" in the screen xml solve my problem
Note that if I use Button instead of ImageButton, elevation is not required.