Thursday, October 10, 2013

Buttons

Let us try to create an activity with a button and a textview

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent" >  
   <TextView  
     android:id="@+id/textView1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text=" "  
     android:textSize="30sp" />  
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_below="@+id/textView1"  
     android:layout_marginTop="18dp"  
     android:text="Click Me" />  
 </RelativeLayout>  



We are using relative layout and we are putting the button below the textview using the xml line android:layout_below="@+id/textView1" for button. 

Let us run the program. 

We do not see any textview. That is because text is set to empty.

 






When the button is clicked, onClick event is fired. We should write a method to handle this event.

Let us write OnClicklistener for the button.


Let us add three lines to the onCreate method of the activity.

        btn = (Button) findViewById(R.id.button1);
        tv = (TextView) findViewById(R.id.textView1);
        btn.setOnClickListener(this);


 and define these two class variables.
        Button btn;
        TextView tv; 

variables. We are defining the OnClickListener of the button to this viz the current activity. So our activity should implement OnClickListener. Modify the class definition to something like

public class MainActivity extends Activity implements OnClickListener

Finally add onClick method to the class

 
   @Override  
   public void onClick(View arg0) {  
     if (arg0.getId() == R.id.button1) {  
       tv.setText( "Button clicked");  
     }  
   }  




This can be even done using xml. In the xml file, we can add this one line for the button -  
android:onClick="somemethodname"
 <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_below="@+id/textView1"  
     android:onClick="showString"  
     android:layout_marginTop="18dp"  
     android:text="Click Me" />  

Now we must define showString method in the activity.

public void showString(View v){
       tv.setText("Button clicked");
}

The signature of the method must be exactly as shown above. It should be public void and it must have exactly one parameter of type View
 
We can set background image of the button to another image using android:background="@drawable/someimage"