Pages

Showing posts with label Widget. Show all posts
Showing posts with label Widget. Show all posts

Wednesday, May 7, 2014

Custom Radio Buttons example in android

In this Post, Custom Radio Buttons using Drawable Resource(color code in selector XML files).



I have create two XML file. one for Radio Buttons Background selector and second for Radio Buttons text color selector.

1. Create One XML file in "res/drawable/rbtn_selector.xml" add below XML code for Radio Button background.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true"><shape>
            <solid android:color="#1c5fab" />

            <stroke android:width="1dp" android:color="#1c5fab" />
        </shape></item>
    <item android:state_checked="false"><shape android:shape="rectangle">
            <solid android:color="#ffffff" />

            <stroke android:width="1dp" android:color="#1c5fab" />
        </shape></item>

</selector>
Note : If we have custom background PNG images for radio Button background then create Selector like below(Put your images in "res/drawable" folder).

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/bg_radio_button_checked" android:state_checked="true"/>
    <item android:drawable="@drawable/bg_radio_button_unchecked" android:state_checked="false"/>

</selector>

2. Create One XML file in "res/drawable/rbtn_textcolor_selector.xml" add below XML code for Radio Buttons Text selector color.(Text Color Selector xml file)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:color="#ffffffff"/>
    <item android:color="#ff1c5fab"/>

</selector>
3. create XML file in layout folder "res/layout/activity_customradiobutton.xml".

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="10dp" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radioAndroid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rbtn_selector"
            android:button="@null"
            android:checked="true"
            android:gravity="center"
            android:padding="5dp"
            android:text="Android"
            android:textColor="@drawable/rbtn_textcolor_selector" />

        <RadioButton
            android:id="@+id/radioiPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rbtn_selector"
            android:button="@null"
            android:gravity="center"
            android:padding="5dp"
            android:text="iPhone"
            android:textColor="@drawable/rbtn_textcolor_selector" />

        <RadioButton
            android:id="@+id/radioWindows"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rbtn_selector"
            android:button="@null"
            android:gravity="center"
            android:padding="5dp"
            android:text="Windows"
            android:textColor="@drawable/rbtn_textcolor_selector" />
    </RadioGroup>

</LinearLayout>
4. Create on activity java file "CustomRadioButtonActivity.java"
I have use setOnCheckedChangeListener for  a callback to be invoked when the checked radio button changed in this group.

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;


public class CustomRadioButtonActivity extends Activity
{

 private RadioGroup radioGroup1;

 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_customradiobutton);

  radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);

  // Checked change Listener for RadioGroup 1
  radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() 
  {
   @Override
   public void onCheckedChanged(RadioGroup group, int checkedId) 
   {
    switch (checkedId) 
    {
    case R.id.radioAndroid:
     Toast.makeText(getApplicationContext(), "Android RadioButton checked", Toast.LENGTH_SHORT).show();
     break;
    case R.id.radioiPhone:
     Toast.makeText(getApplicationContext(), "iPhone RadioButton checked", Toast.LENGTH_SHORT).show();
     break;
    case R.id.radioWindows:
     Toast.makeText(getApplicationContext(), "windows RadioButton checked", Toast.LENGTH_SHORT).show();
     break;
    default:
     break;
    }
   }
  });
 }
}

5. Add your activity class in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.masterapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.limbani.masterapp.CustomRadioButtonActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
Doanload Sample Here

enjoy :)
Thank you.

Wednesday, April 9, 2014

DatePickerDialog in android DialogFragment?

This post I write code for display DatePickerDialog using FragmentDialog.

Generally we display DatePickerDialog using  "onCreateDialog (int id)" Method like below.

//.....
static final int DATE_DIALOG_ID = 999;

//
//

call below code to display DatePickerDialog
showDialog(DATE_DIALOG_ID);

//
//

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
       // set date picker as current date
       return new DatePickerDialog(this, datePickerListener, year, month, day);
    }
   return null;
}
//
//

//we use DatePickerDialog.OnDateSetListener Listner to get selected date like below
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener()
{
    public void onDateSet(DatePicker view, int selectedYear,  int selectedMonth, int selectedDay) {
    }
};




But now "Dialog onCreateDialog(int id)" method deprecated in API level 8. 
So now we can use DialogFragment to display DatePickerDialog and this code working to all android version. I finding DatePickerDialogFragmetn.java class from here.


1. Copy DatePickerDialogFragment.java in your application package.

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.widget.DatePicker;


public class DatePickerDialogFragment extends DialogFragment 
{    
    public static final String YEAR = "Year";
    public static final String MONTH = "Month";
    public static final String DATE = "Day";
    
    private OnDateSetListener mListener;
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mListener = (OnDateSetListener) activity;
    }
    
    @Override
    public void onDetach() {
        this.mListener = null;
        super.onDetach();
    }
    
    @TargetApi(11)
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) 
    {
        Bundle b = getArguments();
        int y = b.getInt(YEAR);
        int m = b.getInt(MONTH);
        int d = b.getInt(DATE);
            
        final DatePickerDialog picker = new DatePickerDialog(getActivity(), getConstructorListener(), y, m, d);
        
        if (hasJellyBeanAndAbove()) {
            picker.setButton(DialogInterface.BUTTON_POSITIVE, 
                    getActivity().getString(android.R.string.ok),
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DatePicker dp = picker.getDatePicker();
                    mListener.onDateSet(dp, 
                            dp.getYear(), dp.getMonth(), dp.getDayOfMonth());
                }
            });
            picker.setButton(DialogInterface.BUTTON_NEGATIVE,
                    getActivity().getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {}
            });
        }
        return picker;
    }
    
    private static boolean hasJellyBeanAndAbove() 
    {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }
    
    private OnDateSetListener getConstructorListener() {
        return hasJellyBeanAndAbove() ? null : mListener;
    }
}


2. Create MainActivity.java

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity implements OnDateSetListener
{
 private TextView tvDisplayDate;
 private Button btnChangeDate;

 private int year;
 private int month;
 private int day;

 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  setCurrentDate();
  button_clickEvent();
 }

 // display current date
 public void setCurrentDate() 
 {
  tvDisplayDate = (TextView) findViewById(R.id.tvDate);
  
  final Calendar c = Calendar.getInstance();
  year = c.get(Calendar.YEAR);
  month = c.get(Calendar.MONTH);
  day = c.get(Calendar.DAY_OF_MONTH);

  Format formatter = new SimpleDateFormat("dd-MM-yyyy");
  String s = formatter.format(c.getTime());
  
  tvDisplayDate.setText(s);  
 }

 public void button_clickEvent() 
 {
  btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
  btnChangeDate.setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    Bundle b = new Bundle();
    b.putInt(DatePickerDialogFragment.YEAR, year);
    b.putInt(DatePickerDialogFragment.MONTH, month);
    b.putInt(DatePickerDialogFragment.DATE, day);
    DialogFragment picker = new DatePickerDialogFragment();
    picker.setArguments(b);
    picker.show(getFragmentManager(), "fragment_date_picker");
   }
  });
 }
 
 @Override
 public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) 
 {
  this.year = year;
  this.month = monthOfYear;
  this.day = dayOfMonth;
  
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.YEAR, year);
  calendar.set(Calendar.MONTH, monthOfYear);
  calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
  
  Format formatter = new SimpleDateFormat("dd-MM-yyyy");
  String s = formatter.format(calendar.getTime());
  
  tvDisplayDate.setText(s);
 }
}


3. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Current Date (dd-MM-yyyy): "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="asdasd"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Change Date" />

</LinearLayout>


4. ScreenShot





Download APK file Here

Reference link for new version DatePickerDialog issues.

- Jelly Bean DatePickerDialog — is there a way to cancel?
- android-android-4-1-emulator-invoking-ondateset-twice-from-datepicker-dialog



Tuesday, March 25, 2014

How to enable/disable buttons of the AlertDialog in Android?

Hello friends,
Today m posting to how enable/disable AlertDialog positive and negative Buttons.


AlertDialog.Builder builder = new AlertDialog.Builder(AddSchedule.this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("Alert dialog title");
builder.setMessage("Dialog message");
builder.setPositiveButton("Button1", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) {
        //DO TASK
    }
});
builder.setNegativeButton("Button2", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) {
        //DO TASK
    }
});

AlertDialog dialog = builder.create();
dialog.show();

//After calling show method, you need to check your condition and 
//enable/ disable buttons of dialog 
if(your_condition_true)
    dialog.getButton(AlertDialog.BUTTON1).setEnabled(false); //BUTTON1 is positive button

For nagative button

dialog.getButton(AlertDialog.BUTTON2).setEnabled(false); //BUTTON2 is negative button

And the setOnShowListener since level 8 API (FroYo), does the same,


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new OnShowListener() 
{
    @Override
    public void onShow(DialogInterface dialog) 
 {
        if(condition)
        ((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }
});
dialog.show();