Monday, 28 October 2013

ToggleButton Example

This example show you how we can work with ToggleButton in android  

Example:






activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:text="ToggleButton Example"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="30dp"
        android:text="ToggleButton" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:src="@drawable/white_page" />

</LinearLayout>


MainActivity.java

package in.androiddevelopmentanddiscussion.togglebutton;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
ToggleButton btn;
ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (ToggleButton)findViewById(R.id.toggleButton1);
img = (ImageView)findViewById(R.id.imageView1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (btn.isChecked()) {
img.setImageResource(R.drawable.smiley);
}
else{
img.setImageResource(R.drawable.sad);
}
}
});
}
}


Download full project from here



Check Android Apps on Google Play

https://play.google.com/store/apps/developer?id=Metro%20App%20Solution&hl=en

 

No comments:

Post a Comment