Reputation: 1122
I have created some buttons in XML and I have method that will onClick open a URL. How do I link this method to my button so that on tap/onClick it will call the method.
Here's the method code:
public void openResource() {
Uri uri = Uri.parse("http://librarywales.org");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
And I have created an instance of my XML Button in the onCreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button libButton = (Button) findViewById(R.id.button1);
}
How do I add that method to the libButton instance?
I have now solved the above issue with the help of 'vins' but when I run this application on the AVD and click on a button it pops up with an android message box saying. 'Unfortunately, ApplicationName has stopped working.'
Anyone know why this is?
Thanks, Dan
Upvotes: 1
Views: 939
Reputation: 4119
public class YourActivity extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button libButton =(Button) findViewById(R.id.button1);
libButton.setOnClickListener(this);
Button OtherButton =(Button) findViewById(R.id.button2);
OtherButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1: openResource();
break;
case R.id.button2: //do something for second button...
default : break;
}
Upvotes: 0
Reputation: 4162
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button libButton = (Button) findViewById(R.id.button1);
libButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if(v.getId()==R.id.button1){
Uri uri = Uri.parse("http://librarywales.org");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
});
}
Upvotes: 0
Reputation: 4661
If you have many buttons with in the page you can use button.setOnClickListener(this);
And override the OnClick() method within the method use Switch statement to match Which View has been selected.It's optimized and efficient way....
Upvotes: 0
Reputation: 109237
Put
android:onClick="openResource"
In your xml file's button's property.
something like,
<Button
android:id="@+id/button1"
.
.
android:onClick="openResource"
/>
Note that this feature only is available on Android 2.1 (API Level 7) and higher
Upvotes: 1
Reputation: 1975
Add this after your button declaration
libButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//open resource method call here...
}
});
Upvotes: 1