Showing posts with label Layouts. Show all posts
Showing posts with label Layouts. Show all posts

Wednesday, October 17, 2012

How to manage Dynamic Height of SlidingDrawer in android ?

Create the custom layout into the main.xml....


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

    <ViewFlipper
        android:id="@+id/ImageFlipper"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <ImageView
            android:id="@+id/imageView0"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />
    </ViewFlipper>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="bottom"
        android:orientation="vertical" >

        <com.example.differentlayout.WrappingSlidingDrawer
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:content="@+id/content"
            android:handle="@+id/handle" >

            <!-- Sliding drawer handle -->

            <ImageView
                android:id="@+id/infoDrawerHandle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@+drawable/info_handle_closed" />

            <!--
        Sliding drawer content: a scroller containing a group of text views
        laid out in a LinearLayout
            -->

            <ScrollView
                android:id="@+id/infoDrawerContent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@+drawable/info_background"
                android:fillViewport="false" >

                <LinearLayout
                    android:id="@+id/infoDrawerContent"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingRight="5dip" >

                    <TextView
                        android:id="@+id/infoTitle"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="#ffffff"
                        android:textSize="16dip"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/infoCreator"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingBottom="10dip"
                        android:textColor="#ffffff"
                        android:textSize="14dip"
                        android:textStyle="italic" />

                    <TextView
                        android:id="@+id/infoDescription"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingBottom="10dip"
                        android:textColor="#ffffff"
                        android:textSize="14dip" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@+string/heading_pro_tip"
                        android:textColor="#ffcc00"
                        android:textSize="14dip"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/infoProTip"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="#ffcc00"
                        android:textSize="14dip" />
                </LinearLayout>
            </ScrollView>
        </com.example.differentlayout.WrappingSlidingDrawer>
    </LinearLayout>

</FrameLayout>



Then create the class for WrappingSlidingDrawer.java......
It will manage the height of the drawer based on the number of elements binded in adapter........


package com.example.differentlayout;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SlidingDrawer;

public class WrappingSlidingDrawer extends SlidingDrawer {

    public WrappingSlidingDrawer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        int orientation = attrs.getAttributeIntValue("android", "orientation", ORIENTATION_VERTICAL);
        mTopOffset = attrs.getAttributeIntValue("android", "topOffset", 0);
        mVertical = (orientation == SlidingDrawer.ORIENTATION_VERTICAL);
    }

    public WrappingSlidingDrawer(Context context, AttributeSet attrs) {
        super(context, attrs);

        int orientation = attrs.getAttributeIntValue("android", "orientation", ORIENTATION_VERTICAL);
        mTopOffset = attrs.getAttributeIntValue("android", "topOffset", 0);
        mVertical = (orientation == SlidingDrawer.ORIENTATION_VERTICAL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize =  MeasureSpec.getSize(widthMeasureSpec);

        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize =  MeasureSpec.getSize(heightMeasureSpec);

        if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
            throw new RuntimeException("SlidingDrawer cannot have UNSPECIFIED dimensions");
        }

        final View handle = getHandle();
        final View content = getContent();
        measureChild(handle, widthMeasureSpec, heightMeasureSpec);

        if (mVertical) {
            int height = heightSpecSize - handle.getMeasuredHeight() - mTopOffset;
            content.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, heightSpecMode));
            heightSpecSize = handle.getMeasuredHeight() + mTopOffset + content.getMeasuredHeight();
            widthSpecSize = content.getMeasuredWidth();
            if (handle.getMeasuredWidth() > widthSpecSize) widthSpecSize = handle.getMeasuredWidth();
        }
        else {
            int width = widthSpecSize - handle.getMeasuredWidth() - mTopOffset;
            getContent().measure(MeasureSpec.makeMeasureSpec(width, widthSpecMode), heightMeasureSpec);
            widthSpecSize = handle.getMeasuredWidth() + mTopOffset + content.getMeasuredWidth();
            heightSpecSize = content.getMeasuredHeight();
            if (handle.getMeasuredHeight() > heightSpecSize) heightSpecSize = handle.getMeasuredHeight();
        }

        setMeasuredDimension(widthSpecSize, heightSpecSize);
    }

    private boolean mVertical;
    private int mTopOffset;
}

Wednesday, August 1, 2012

How to get the Dimension of layouts in android ?


In Android, you attach a view tree to your Actitity in order to be able to interact with the UI.
Once this is done, you can get references to your widgets (views) using a call like this from your Activity:
TextView t = (TextView) findViewById(R.id.txtName);

Now, views all sport a method like this: t.getHeight()
Which, presumably returns the actual height of that view element. Problem is, this method invariably returns zero.

At first I thought it was because I was calling this during the onCreate() method in my activity class. Perhaps the layout wasn't fully calculated at this time. So I moved my code to the onResume() method. This method is called whenever the activity is entered or re-entered. But again, no luck. Strange, as the layout at this point should be fully ready to display. I think there's a bug here in Android (I'm at version 2.2 currently.)

Luckily, I accidentally hit the search button while running a test on my EVO and, lo and behold, the height values I was trying to report on a TextView in my layout suddenly had non-zero values in them. Obviously, some sort of layout process had been forced, and the state of the view tree had been updated.

How can I get notified when the layout is fully calculated? The short answer is to attached a listener for a callback when the layout is calculated. Here's what it looks like.

@Override
public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  RelativeLayout vMain = (RelativeLayout) 
     this.getLayoutInflater().inflate(R.layout.main, null);
  vMain.getViewTreeObserver().addOnGlobalLayoutListener(
  new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {
      DisplayLayoutDimensions();
    }
  });
  setContentView(vMain);
}




public void DisplayLayoutDimensions()
{
  StringWriter sw = new StringWriter(1000);
  PrintWriter out = new PrintWriter(sw);
  TextView t = (TextView) findViewById(R.id.textview);
  ImageView img = (ImageView) findViewById(R.id.hp67);
  out.printf("\nImage Drawable\n");
  out.printf("ImageView Height dp: %d\n", img.getHeight());
  out.printf("ImageView Measured Height dp: %\n",
     img.getMeasuredHeight());
  t.setText(sw.toString());
}

Sunday, July 22, 2012

Get Screen Size Pixels per Inch Android example ?


The exact physical pixels per inch of the screen,Get size of pixel,Get DPI,Get count of pixels per inch

float mXDpi;
float mYDpi;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mXDpi = metrics.xdpi; // The exact physical pixels per inch of the screen in the X dimension.
 mYDpi = metrics.ydpi;
float  mMetersToPixelsX = mXDpi / 0.0254f; // 1 inch == 0.0254 metre
float  mMetersToPixelsY = mYDpi / 0.0254f;

Sunday, July 15, 2012

Get drawable Id based on string Android?


here is a code snippet on how to do it:


public static int getDrawable(Context context, String name)
{
Assert.assertNotNull(context);
Assert.assertNotNull(name);

return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}

Friday, June 15, 2012

Design Layout For Multiple Screens in android?


You need to create different layout for diff screen size. Support all screen you need to create following layout:

1-Low density Small screens QVGA 240x320 (120dpi):
layout-small-ldpi (240x320)
layout-small-land-ldpi (320x240)

2-Low density Normal screens WVGA400 240x400 (x432) (120dpi):
layout-ldpi  (240 x 400 )
layout-land-ldpi  (400 x 240 )

3-Medium density Normal screens HVGA 320x480 (160dpi):
layout-mdpi (320 x 480 )
layout-land-mdpi (480 x 320 )

4-Medium density Large screens HVGA 320x480 (160dpi):
layout-large-mdpi (320 x 480 )
layout-large-land-mdpi (480 x 320)

5-Galaxy Tab ( 240 dpi ):
layout-large  (600 x 1024)
layout-large-land  (1024 x 600)

6-High density Normal screens WVGA800 480x800 (x854) (240 dpi):
layout-hdpi (480 x 800)
layout-land-hdpi (800 x 480)

7-Xoom (medium density large but 1280x800 res) (160 dpi):
layout-xlarge (800 x 1280)
layout-xlarge-land (1280 x 800)

8- Other

layout-normal-mdpi -> 320x480
layout-normal-hdpi -> 800x480 and 854x480 (adjusted in the code)
layout-normal-ldpi -> 400x240
layout-large-mdpi -> 800x480 tablet (mostly the same as the layout-normal-hdpi layout, but needs to be in this folder)
layout-small-ldpi -> 320x240


Also add following code in .manifest file:

<supports-screens                              
    android:smallScreens="true"                  
    android:normalScreens="true"      
    android:largeScreens="true"          
    android:xlargeScreens="true"          
    android:anyDensity="true" />

Thursday, May 31, 2012

Custom fonts for Webview And Textviewv in android?


In Android, the three default font options are monospace, sans serif and serif. You do have some flexibility with adding effects to the default fonts, but without custom fonts, you are pretty limited in how text in your Android appears to your users. Luckily, it’s fairly straightforward to set a custom font. You can find plenty of free custom fonts at sites likedafont.com – just download the .ttf file for the font of your choice, and add it to the assets/fonts directory of your codebase (create the directory if it doesn’t exist already).
Custom Fonts in Views
If, for example, you’d like to set the font for a TextView with id=name, it’s as simple as adding the following to your code:

TextView name = (TextView) findViewById(R.id.name);
Typeface  typeface = Typeface.createFromAsset(getContext().getAssets()"fonts/customFont.ttf");
name.setTypeface(typeface)
;


That’s fine when you have just one or two TextViews with custom fonts, but it gets to be a pain when you want customized fonts on all your TextViews. That’s a lot of boilerplate code to have in your activities! It would be convenient to be able to specify the font name in xml. To do this, you can extend TextView:

public class CustomTextView extends TextView {
private static final DEFAULT_FONT="defaultFont.ttf";

  public CustomTextView(Context context) {
    this(context, null);
  }

  public CustomTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, 0, 0);
    String fontName = arr.getString(R.styleable.CustomTextView_fontName);
    // Sets to a default font if none is specified in xml
    if (fontName == null) {
      fontName = DEFAULT_FONT;
    }
    setFont(fontName);
  }

  private void setFont(String fontName) {
    Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontName);
    setTypeface(typeface);
  }
}


In your attrs.xml (in res/values/, create the xml file if it doesn’t exist already), add an attribute for CustomTextView as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextView">
<attr name="fontName" format="string"/>
</declare-styleable>
</resources>


Now you can add a custom font to a TextView in xml, without any additional code to your activities:

<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:example="http://schemas.android.com/apk/res/com.example.customfonts"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
<com.example.customfonts.CustomTextView
       example:fontName="customFont2.ttf"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" />
</LinearLayout>


That’s it! Now you can easily set custom fonts for views in xml.
Custom Fonts in WebViews
For webviews, you still want to copy the .ttf file into your assets/fonts directory, and then you can create new font-faces in your css and use them by setting font-family:

<style type="text/css"> 
    @font-face { 
        font-family:"customFont1"; 
        src:url('file:///android_asset/fonts/customFont.ttf');
    }
    @font-face { 
        font-family:"PTS55F"; 
        src:url('file:///android_asset/fonts/customFont2.ttf');
    }

    body { font-family:'customFont'; }
    h1 { font-family:'customFont2'; }
</style>


Using custom fonts gives you a lot more control over the visual appearance of your application, but when don’t get carried away — using too many random fonts can make an app seem very disjointed. In general, try to use at most a few fonts that go well together. To get you started, here are 40 free designer fonts.

Friday, March 23, 2012

How to make the scrollable TextView in android?



public class MainActivity extends Activity {
/** Called when the activity is first created. */

private TextView mTextView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.textView1);
mTextView
.setText("this is for testing \nthis is for testing \nthis is for testing \nthis is for testing \nthis is for testing \nthis is for testing \n");

mTextView.setMovementMethod(new ScrollingMovementMethod() {
public void onTakeFocus(TextView widget, Spannable text, int dir) {

}

@Override
public boolean onKeyDown(TextView widget, Spannable buffer,
int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
down(widget, buffer);
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
up(widget, buffer);
}
return true;
default:
return super.onKeyDown(widget, buffer, keyCode, event);
}
}
private int getScrollAmount(TextView widget) {
final int visibleLineCount = (int) ((1f * widget.getHeight()) / widget
.getLineHeight());
int scrollAmount = visibleLineCount - 1;
if (scrollAmount < 1) {
scrollAmount = 1;
}
return scrollAmount;
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:

return true;
case KeyEvent.KEYCODE_DPAD_UP:
mTextView.dispatchKeyEvent(event);
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
}


Tuesday, March 20, 2012

How to scroll vertically and Horizontally in android?

This is what i have done to fix the same..

       <LinearLayout 

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

              <HorizontalScrollView                                                                         
                  android:id="@+id/horizontal_scroll_view"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:scrollbars="horizontal">
                                                                          
                  <ScrollView                                                                          
                      android:id="@+id/vertical_scroll_view"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:scrollbars="vertical">
                                                               
                      <LinearLayout                                                       

                          android:id="@+id/linear_layout"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content">

                                  <!--childrens go here..
                                          I have used an image view for demonstration-->

                      </LinearLayout>
                     
                  </ScrollView>
                 
              </HorizontalScrollView>          
        </LinearLayout>

Probably  the vertical scroll bar may not be visible at first. However once you reach the extreme end of x-axis(right), vertical scroll can be seen. If you want to see both @ a time set width & height of scrollviews  respectively
          Also you may interchange the order of the scrollviews. By doing so i found no difference. However make sure your vertical scroll view hosted by a LinearLayout(with vertical orientation) and any children should be hosted by a single LinearLayout within vertical ScrollView.

Sunday, March 18, 2012

How to display escape charaters in android?


"  ----------------->  &quot;
'  ------------------>  &apos;
< ----------------->  &lt ;
> ----------------->  &gt;
& ----------------->  &amp;

For example ......
<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="You&apos;ve made it back after a notification, yay!" />

It will print "You've made it back after a notification,yay!" in TextView

Thursday, March 15, 2012

How to set padding programmatically in dp(dip) in Android?


final float scale = getResources().getDisplayMetrics().density;
int padding_5dp = (int) (5 * scale + 0.5f);
int padding_20dp = (int) (20 * scale + 0.5f);
int padding_50dp = (int) (50 * scale + 0.5f);
RadioButton rb = new RadioButton(this);
rb.setText("My Radio Button");
rb.setLayoutParams(new LayoutParams(padding_50dp,padding_50dp));
rb.setPadding(padding_20dp,padding_5dp,padding_5dp,padding_5dp);

public void setPadding (int left, int top, int right, int bottom)
Sets the padding. The view may add on the space required to display the scrollbars, depending on the style and visibility of the scrollbars. So the values returned from getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom() may be different from the values set in this call.

Related XML Attributes
  • android:padding
  • android:paddingBottom
  • android:paddingLeft
  • android:paddingRight
  • android:paddingTop

Parameters
  • left the left padding in pixels
  • top the top padding in pixels
  • right the right padding in pixels
  • bottom the bottom padding in pixels

How to remove view from layout in android dynamically



Android remove view from parent


View myView = findViewById(R.id.hiddenLayout);
ViewGroup parent = (ViewGroup) myView.getParent();
parent.removeView(myView);

Android remove all child views


LinearLayout formLayout = (LinearLayout)findViewById(R.id.formLayout);
formLayout.removeAllViews();

Tuesday, February 21, 2012

How to Set TextView Shadow in Android?


Text Shadow

You can use three different attributes to customize the appearance of your text shadow:
  • android:shadowColor Shadow color in the same format as textColor.
  • android:shadowRadius Radius of the shadow specified as a floating point number.
  • android:shadowDx The shadow’s horizontal offset specified as a floating point number.
  • android:shadowDy The shadow’s vertical offset specified as a floating point number.
The floating point numbers don’t have a specific unit – they are merely arbitrary factors.
<TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="A light blue shadow."
            android:shadowColor="#00ccff"
            android:shadowRadius="1.5"
            android:shadowDx="1"
            android:shadowDy="1"
            />


Using spinner.setSelection & finding the spinner doesn't show the selected item when closed in android?


Ok, I've just spent a couple of hours trying to figure this out, and now I have, I thought I'd share the incredibly simple solution with you.

The issue: I was needing to set a Spinner's 
selected item via code, but found when calling the Spinner's setSelection method and passing in the position to set it to, something odd would happen, the closed spinner would appear blank, yet, when clicking on it, the item I've asked to be selected would be correctly located at the top of the spinner.

It looks like a Spinner is not told to redraw when using
.setSelection(position), what you have to do is call.setSelection(int position, boolean animate) unless you want your selection to happen silently behind the scenes.

Odd, but easily sorted out.

The incredibly simple solution:

This 
won't show the fact that the Spinner selection has been set:

spnIngredients.setAdapter(ingredientAdapter);
spnIngredients.setSelection(position);

This will:

spnIngredients.setAdapter(ingredientAdapter);
spnIngredients.setSelection(pos, true);