Tuesday 1 December 2015

Dynamically set height of listview

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        // pre-condition        return;
    }
    if (listAdapter.getCount() <= 2) {
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
}



In the main Acticity use this Utility class to change the listview height.

 phraseListView=(ListView)findViewById(R.id.phrase_listview);
 phraseAdapter=new PhraseListAdapter(this);
phraseListView.setAdapter(phraseAdapter);
setListViewHeightBasedOnChildren(phraseListView);      

 



2) If Adapter item's height is dynamic then use this function before nofitydataSetChanged()

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        return;
    }
    int totalHeight = 0;
    int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)) + 10;
    Log.e("HEIGHT","HEIGHT::::::"+params.height);
    listView.setLayoutParams(params);
    listView.requestLayout();

}

Monday 30 November 2015

View Pager for show Fullscreen image with customize width & height of activity

1) FullScreenViewActivity.java
=============================
package com.bluegreen.masmas.customer.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import com.bluegreen.masmas.customer.R;
import com.bluegreen.masmas.customer.Utility.Consts;
import com.bluegreen.masmas.customer.adapter.FullScreenImageAdapter;
import com.bluegreen.masmas.customer.model.DealDetailImagesModel;
import java.util.ArrayList;

public class FullScreenViewActivity extends Activity implements OnClickListener {
   public FullScreenImageAdapter adapter;
   private ViewPager viewPager;
   public static final String VIEW_PAGER_OBJECT_TAG = "image#";
   int position;
   public static int intPagePosition;
   private ImageView imgClose;
   private ArrayList<DealDetailImagesModel> alstDealImages;

   @Override   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
      FullScreencall();
      setContentView(R.layout.activity_fullscreen_view);
      int width = this.getResources().getDisplayMetrics().widthPixels;
      int height = this.getResources().getDisplayMetrics().heightPixels;
      height = height-150;
      
      WindowManager.LayoutParams params = getWindow().getAttributes();  
      params.x = -20;  
      params.height = width;
      params.width = width;  
      params.y = -10;  
      this.getWindow().setAttributes(params);
      alstDealImages = new ArrayList<DealDetailImagesModel>();

      viewPager = (ViewPager) findViewById(R.id.pager);
      viewPager.setPageMargin(20);
      viewPager.setPageMarginDrawable(R.color.black);
      imgClose = (ImageView) findViewById(R.id.imgClose);
      imgClose.setOnClickListener(this);

      Intent intent = getIntent();
      position = intent.getExtras().getInt(Consts.IMAGE_DEAL_POS, 0);
      viewPager.setCurrentItem(position);
      Bundle args = intent.getBundleExtra(Consts.IMAGE_BUNDLE);
      alstDealImages = (ArrayList<DealDetailImagesModel>) args.getSerializable(Consts.IMAGE_DEAL_ARRAY);
      adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,alstDealImages, width, height);
      viewPager.setAdapter(adapter);
      viewPager.setCurrentItem(position);
   }

   @Override   protected void onResume() {
      super.onResume();
      FullScreencall();
   }

   public void FullScreencall() {
      if (Build.VERSION.SDK_INT < 19) {
         View v = this.getWindow().getDecorView();
         v.setSystemUiVisibility(View.GONE);
      } else {
         View decorView = getWindow().getDecorView();
         int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
         decorView.setSystemUiVisibility(uiOptions);
      }
   }

   @Override   public void onClick(View v) {
      switch (v.getId()) {
      case R.id.imgClose:
         finish();
         break;

      default:
         break;
      }
   }
}


2) FullScreenImageAdapter.java
==============================
package com.bluegreen.masmas.customer.adapter;

import android.content.Context;
import android.graphics.Matrix;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bluegreen.masmas.customer.R;
import com.bluegreen.masmas.customer.model.DealDetailImagesModel;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class FullScreenImageAdapter extends PagerAdapter {
    private ArrayList<DealDetailImagesModel> alstImages;
    private LayoutInflater inflater;
    private Context mContext;
    ImageView imgBig;
    public static ImageView imgClose = null;
    public int width, height;

    public FullScreenImageAdapter(Context mContext, ArrayList<DealDetailImagesModel> alstImages, int width, int height) {
        this.mContext = mContext;
        this.alstImages = alstImages;
        this.width = width;
        this.height = height;
    }

    public int getCount() {
        return this.alstImages.size();
    }

    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    Matrix imageMatrix;
    public Object instantiateItem(ViewGroup container, int position) {
        inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.layout_fullscreen_image, container, false);

        imgBig = (ImageView) view.findViewById(R.id.imgBig);
        imgBig.getLayoutParams().width = (int) width;
        imgBig.getLayoutParams().height = (int) (width);

        Picasso.with(mContext).load(alstImages.get(position).getStrImage()).into(imgBig);

        ((ViewPager) container).addView(view);
        return view;
    }

    @Override    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((View) object);
    }
}

3) activity_fullscreen_view.xml
===============================
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@color/black"    android:orientation="vertical" >

    <FrameLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_centerInParent="true"        android:gravity="center" >

        <android.support.v4.view.ViewPager            android:id="@+id/pager"            android:layout_width="fill_parent"            android:layout_height="fill_parent" >
        </android.support.v4.view.ViewPager>

        <ImageView            android:id="@+id/imgClose"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="right|top"            android:contentDescription="@string/app_name"            android:src="@drawable/delete" />
    </FrameLayout>

</RelativeLayout>

4) layout_fullscreen_image.xml
===============================
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/layout_root"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@color/black" >
    <ImageView        android:id="@+id/imgBig"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:adjustViewBounds="true"        android:contentDescription="@string/app_name"        android:gravity="center"        android:scaleType="fitXY"        android:src="@drawable/list_noimg" />

</RelativeLayout>

Monday 28 September 2015

CustomFont android

Good link:::

http://amitandroid.blogspot.in/2013/01/how-to-use-external-fonts-therough.html


1) add font file in assets folder
2) create class TextNormal.java in package com.app.utility.

package com.app.utility;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;


public class TextNormal extends TextView {

public TextNormal(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}

public TextNormal(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public TextNormal(Context context) {
super(context);
init();
}

public void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"segoeui_0.ttf");
setTypeface(tf);
}
}
}
3) in xml  add your textview like

 <com.app.utility.TextNormal
                android:id="@+id/txtRemeberMe"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_marginLeft="@dimen/val_5"
                android:gravity="left"
                android:padding="@dimen/txt_padding_left"
                android:text="@string/remember_me"
                android:textSize="@dimen/txt_small_size" />

Tuesday 7 July 2015

Get Location using GPS

http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

1)GPSTracker.java
==============
package com.demo.test;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }
   
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }    
    }
   
    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
       
        // return latitude
        return latitude;
    }
   
    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
       
        // return longitude
        return longitude;
    }
   
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
   
    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
   
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

2)AndroidGPSTrackingActivity.java
==========================

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidGPSTrackingActivity extends Activity {
     
    Button btnShowLocation;
     
    // GPSTracker class
    GPSTracker gps;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
         
        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View arg0) {       
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);
                // check if GPS enabled    
                if(gps.canGetLocation()){
                     
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                     
                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();   
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }
                 
            }
        });
    }
     
}

3)Manifest.java
================

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />   
    <uses-permission android:name="android.permission.INTERNET" />