Reputation: 545
I know this is the basic stuff but I couldn't figure it out. Here is my code:
public class test extends Activity{
private static final String TAG = "test";
private Button Test;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.v(TAG,"onCreate is called.");
this.setContentView(R.layout.main);
Test= (Button)this.findViewById(R.id.Test);
Test.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "onClick Entered.");
// Perform action on click
}
});
setContentView(R.layout.main);
}
}
I can see the first log "OnCreate" but the button click event listener doesn't seem to work because I can't see "OnClick Entered". Where did I do wrong?
Thanks
Upvotes: 0
Views: 4216
Reputation: 46844
You are calling setContentView
twice, the second time after you have set up your on click listener. This means that the view that you add the listener to is no longer visible, it is replaced with a different instance of the view. Remove the second setContentView
.
Upvotes: 5
Reputation: 134664
A few comments / things to try:
You have your naming conventions backwards. You should be naming your activity in title case, your variables in camel case (e.g. your activity "test.java" should be Test.java, your Button Test
should be Button test
). That's not your problem, but just something to keep in mind.
You're calling super.onCreate()
twice. I really don't know what effect that has, but it shouldn't be there. You're also calling setContentView()
twice. One call to onCreate, one call to setContentView is all you should have. EDIT: Apparently three times, per Jems's comment.
In main.xml, do you have a Button with an id of test? (i.e. android:id="@+id/test"
)
Upvotes: 1
Reputation: 13140
Where is showTrafficButton defined? Are you sure that shouldn't be:
Button showTrafficButton = (Button)this.findViewById(R.id.Test);
Upvotes: 0