Reputation: 66
following some tutorials i encountered a strange error...when i start it on my device it crashes instantly...why? Also i tried 3 different ways to use onClick... whats the difference between those 3? (the other 2 are commented out)
<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button1"
android:onClick="sendMessage" />
package com.example.a2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity
{
String CopyText;
String editText1;
String editText2;
final Button button1 = new Button(this);
public void sendMessage(View view)
{
button1.setText(editText1);
}
/*
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
}
});
/*
/*
OnClickListener buttonListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
button1.setText(editText1);
}
};
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Upvotes: 0
Views: 89
Reputation: 24853
try this..
do that initialization and click inside your onCreate
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Cilcked", Toast.LENGTH_SHORT).show();
}
});
}
EDIT :
When an activity starts its life onCreate() is called. It is called only once in the lifecycle of an activity.
If you save the state of the application in a bundle (typically non-persistent, dynamic data in onSaveInstanceState), it can be passed back to onCreate if the activity needs to be recreated (e.g., orientation change) so that you don't lose this prior information. If no data was supplied, savedInstanceState is null.
Upvotes: 1
Reputation: 3210
first : solution to make button without any reference to layout and try to change the test of it
second : the button id in layout is button_send and you try to access it with button1
and i think the third solution related to second problem
Upvotes: 1