Tuesday, 3 July 2012

Create a Button click without using a onClickListener in android example

Create a Button click without using a onClickListener in android example





In this example we are not using a onClickListner for giving action to a button ,in this example we are just give the reference to main.xml  for the onClick
















Here is the code for the main.xml



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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    <Button 
    android:id="@+id/button1"
    android:text="hai"
    android:layout_width="62dip"
    android:layout_height="62dip"
    android:layout_marginLeft="75dip"
    android:layout_marginTop="75dip"
    android:onClick="sendmsg"/>
</LinearLayout>




the method name in the main activity which is used for giving action have the same name as that of the main.xml -onclick .that is in main actvity we have methode named sendmsg().one thing you must notice that this method must be public and return a void return value




ButtonclickActivity


package a.b;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ButtonclickActivity extends Activity {
 Button b1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        b1=(Button)findViewById(R.id.button1);
        
        
    }
    public void sendmsg(View v)
    {
    if (v==b1)
    {
    Toast.makeText(this, "haiiiiii",Toast.LENGTH_LONG).show();
    }
    }
    
}















No comments:

Post a Comment