Monday, 12 March 2012

Single textview with multiple action

We can use single textview for:

1.  Different textsizes.
2.  Different colors.
3.  Click event.
4.  Linking with URL etc.

private void prepareStylishText ( TextView view ) {
        SpannableStringBuilder spanTxt = new SpannableStringBuilder("Different");

        //set the text clickable.
        spanTxt.setSpan(new ClickableSpan() {

            public void onClick(View widget) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Different style text in android.",
                0, spanTxt.length(), 0 );

        //set the text color.
        spanTxt.setSpan(new ForegroundColorSpan(Color.RED),
                0, spanTxt.length(), 0 );

        //add more text.
        spanTxt.append(" style");
        spanTxt.setSpan(new ForegroundColorSpan(Color.BLUE),
            spanTxt.length() - " style".length(), spanTxt.length(), 0 );

        spanTxt.append(" text with single textview in");

        spanTxt.setSpan(new ForegroundColorSpan(Color.BLACK),
            spanTxt.length() - " text with single textview in".length(), spanTxt.length(), 0 );

        spanTxt.append(" android.");

        //make the textsize 2 times.
        spanTxt.setSpan(new RelativeSizeSpan(2f), spanTxt.length() - " android".length(), spanTxt.length(), 0  );

        //make the link.
        spanTxt.setSpan(new URLSpan(""), spanTxt.length() - " android".length(), spanTxt.length(), 0 );

        //set the color after the link else the link color will override it.
        spanTxt.setSpan(new ForegroundColorSpan(Color.GREEN),
                spanTxt.length() - " android".length(), spanTxt.length(), 0 );

        //make click and url to work.
        view.setText(spanTxt, BufferType.SPANNABLE);

 Note: You can also use SpannableString in place of SpannableStringBuilder.

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Tuesday, 6 March 2012

Fragment Dialog and Date-Time Picker

With the fragment use we often need to use dialog with fragment. Here we will see how to use dialog with fragment and How to use Date-Time picker with the fragment.

Note: Check Fragment.

1. Extend DialogFragment:

public class CustomDialogFragment extends DialogFragment{
       //Define constants for date-time picker.
       public final int DATE_PICKER = 1;
       public final int TIME_PICKER = 2;
       public final int DIALOG = 3;

2. Add constructor with Fragment argument as It will let know over which fragment, the dialog should be shown.

private Fragment mCurrentFragment;
public CustomDialogFragment ( Fragment fragment ) {
        mCurrentFragment = fragment;

3.  Override onCreateDialog:

public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle bundle = new Bundle();
        bundle = getArguments();
        int id = bundle.getInt("dialog_id");
        switch (id) {
        case DATE_PICKER:
            return new DatePickerDialog(getActivity(),
                    (OnDateSetListener)mCurrentFragment, bundle.getInt("year"),
                    bundle.getInt("month"), bundle.getInt("day"));
       case TIME_PICKER:
            return new TimePickerDialog(getActivity(),
                    (OnTimeSetListener)mCurrentFragment,          bundle.getInt("hour"),
                    bundle.getInt("minute"), false);

       case DIALOG:
       //Define your custom dialog or alert dialog here and return it.
       return dialog;

Note: Implement OnDateSetListener, OnTimeSetListener on Fragment.

4. Show the dialog:

CustomDialogFragment dialog = new CustomDialogFragment(YourFragment.this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);, "dialog");

Note: For detail description follow the link.

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Monday, 5 March 2012

Useful stuff

Here is nothing new but I wanted to bind some useful stuff that I could not find in one place.

1. Invoke the device's gallery and get the Image/video URI. 

private void invokeGallery () {
     Intent intent = new Intent();
     startActivityForResult(intent, 001);

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if ( requestCode == 001 && data != null && data.getData() != null ) {
            URi imageUri = data.getData();
            imageview.setImageURI(imageUri );

2. Launch default contact picker and get the contact details.

private void launchContactPicker() {
        Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
        startActivityForResult(contactPickerIntent, 1001);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if ( requestCode == 1001 ) {
      Bundle _data = data.getExtras();
      Set<String> keys = _data.keySet();
      Iterator<String> iterate = keys.iterator();
      if ( iterate.hasNext() ) {
         String key =;
         String contactName = _data.get(key).toString();
      //To query Content Provider for contact number:
      Cursor cursor = getContentResolver().query(android.provider.ContactsContract.Contacts.CONTENT_URI, null,    android.provider.ContactsContract.Contacts.DISPLAY_NAME + "=?", new String[]{contactName }, null);    
      //To query the Content Provider for Email ID's:

      //Using above cursor:
      String id = cursor .getString(cursor .getColumnIndex(android.provider.ContactsContract.Contacts._ID));
      Cursor emailCursor = getContentResolver().query(android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, android.provider.ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = " + id, null, null);

      if(emailCursor .getCount() > 0){
         emailCursor .moveToFirst();
         do {
             String _emailId = emailCursor.getString(emailCursor        .getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Email.DATA));            }while(mCursor.moveToNext());


3. Get device resolution and desity.

DisplayMetrics metrics = new DisplayMetrics();
    case DisplayMetrics.DENSITY_LOW:
    case DisplayMetrics.DENSITY_MEDIUM:
    case DisplayMetrics.DENSITY_HIGH:
int screenWidth = metrics .widthPixels;
int screenHeight = metrics .heightPixels;

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers