Thanks for all the help. It turns out that I was calling the click handler in the wrong activity.
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!
Решение
Другие советы
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