Saturday, 27 July 2013

Slider example

You create slider look like in facebook.
follow below steps ,


create  horz_scroll_menu.xml file 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/menu"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:background="#2A323D"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2A323D"
        android:scrollbars="none" >
    </ListView>

</LinearLayout>


create link.xml 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/link"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginLeft="16dp"
        android:padding="10dp"
        android:textSize="16sp"
        android:textStyle="bold"
        android:textColor="@android:color/white"
        android:text="">
    </TextView>
   
</RelativeLayout>


create screen_facebook_slider.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <RelativeLayout
        android:id="@+id/tabBar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/blue_gradient_header"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/BtnSlide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="false"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:layout_marginLeft="8dp"
            android:padding="4dp"
            android:background="@drawable/menu"
            android:text=""/>

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="wrap_content"
            android:layout_height="32dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="Facebook Slider"
            android:textColor="@android:color/white"
            android:textSize="22sp"
            android:textStyle="bold"
            android:typeface="sans" >

        </TextView>

     </RelativeLayout>
    <WebView 
    android:id="@+id/webView"
    android:layout_below="@+id/tabBar"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="visible"
    />

</RelativeLayout>


create screen_scroll_with_list_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<com.android.facebookslider.FacebookSlideView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="0px"
    android:background="#00ffffff"
    android:fadingEdge="none"
    android:fadingEdgeLength="0px"
    android:padding="0px"
    android:scrollbars="none" >

    <LinearLayout
        android:id="@+id/top"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_margin="0px"
        android:background="#ffffffff"
        android:orientation="horizontal"
        android:padding="0px" >
    </LinearLayout>

</com.android.facebookslider.FacebookSlideView>



create Config.class

import java.util.ArrayList;
import com.android.model.WebAddress;

public class Config {
   
    static ArrayList<WebAddress> address = null;

    public static ArrayList<WebAddress> createAddress() {
        address = new ArrayList<WebAddress>();
        address.add(new WebAddress("Google","http://www.google.com"));
        address.add(new WebAddress("Yahoo","http://www.yahoo.co.in"));
        address.add(new WebAddress("Gmail","http://www.gmail.com"));
        address.add(new WebAddress("Facebook","http://www.facebook.com"));
        address.add(new WebAddress("My Blog","http://divine4android.blogspot.in/"));
        return address;

    }

}


create WebAddress.class

public class WebAddress {
    String name;
    String url;
   
   
    public WebAddress(String name, String url) {
        this.name = name;
        this.url = url;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
   
}


create Adapter MenuAdapter.class

import java.util.ArrayList;
import com.android.model.WebAddress;
import com.example.facebookslider.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MenuAdapter extends ArrayAdapter<WebAddress> {

    Context context;
    int layoutResourceId;  
     ArrayList<WebAddress> data=new ArrayList<WebAddress>();
    public MenuAdapter(Context context, int layoutResourceId, ArrayList<WebAddress> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        RegardingTypeHolder holder = null;
      
        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
          
            holder = new RegardingTypeHolder();
            holder.textName=(TextView)row.findViewById(R.id.link);
            row.setTag(holder);
        }
        else
        {
            holder = (RegardingTypeHolder)row.getTag();
        }
      
        WebAddress address = data.get(position);
        holder.textName.setText(address.getName());
        return row;
      
    }
  
    static class RegardingTypeHolder
    {
       
        TextView textName;
    }
}

 

create FacebookSlider.class

import java.util.ArrayList;
import java.util.Stack;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.android.adapter.MenuAdapter;
import com.android.facebookslider.FacebookSlideView;
import com.android.facebookslider.FacebookSlideView.SizeCallback;
import com.android.model.WebAddress;
import com.android.utilities.Config;
import com.example.facebookslider.R;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class FacebookSlider extends Activity {
    FacebookSlideView scrollView;
    MenuAdapter menuAdapter;
    View menu;
    View app;
    Button btnSlide;
    static boolean menuOut = false;
    boolean isScan = false;
    Handler handler = new Handler();
    int btnWidth;
    ArrayList<WebAddress> address = new ArrayList<WebAddress>();
    WebView webView;
    ProgressDialog mProgress;
    boolean loadingFinished = true;
    boolean redirect = false;
    AlertDialog.Builder alert;
    boolean isWebHistory = false;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if( Build.VERSION.SDK_INT >= 9){
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

            StrictMode.setThreadPolicy(policy);
        }
       
        LayoutInflater inflater = LayoutInflater.from(this);
        scrollView = (FacebookSlideView) inflater.inflate(R.layout.screen_scroll_with_list_menu, null);
        setContentView(scrollView);

        final Stack stack=new Stack();
        menu = inflater.inflate(R.layout.horz_scroll_menu, null);
        app = inflater.inflate(R.layout.screen_facebook_slider, null);
        webView =(WebView) app.findViewById(R.id.webView);
        ViewGroup tabBar = (ViewGroup) app.findViewById(R.id.tabBar);
       
        address = Config.createAddress();
        menuAdapter = new MenuAdapter(this,R.layout.link, address);
        ListView listView = (ListView) menu.findViewById(R.id.list);
        //ViewUtils.initListView(this, listView, "Menu ", 8, android.R.layout.simple_list_item_1);
        listView.setAdapter(menuAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Context context = view.getContext();
                isWebHistory = true;
                webView.setVisibility(0);
                webView.getSettings().setJavaScriptEnabled(true);
                menuOut = true;
                scrollWebviw(scrollView, menu);
                // force web view to open inside application
                mProgress = ProgressDialog.show(FacebookSlider.this, "Loading", "Please wait for a moment...");
                webView.setWebViewClient(new MyWebViewClient());
                menuOut = false;
                stack.push(address.get(position).getName());
                Log.d("The contents of Stack is" , stack.toString());
                openURL(address.get(position).getUrl());
                webView.requestFocus(View.FOCUS_DOWN);
                webView.setOnTouchListener(new View.OnTouchListener() {
                       @Override
                    public boolean onTouch(View v, MotionEvent event) {
                           switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                        case MotionEvent.ACTION_UP:
                            if (!v.hasFocus()) {
                                v.requestFocus();
                            }
                            break;
                    }
                    return false;
                    }
                });
              
            }

        });
       
        btnSlide = (Button) tabBar.findViewById(R.id.BtnSlide);
      
        btnSlide.setOnClickListener(new ClickListenerForScrolling(scrollView, menu));

        final View[] children = new View[] { menu, app };

        // Scroll to app (view[1]) when layout finished.
        int scrollToViewIdx = 1;
       
        scrollView.initViews(children, scrollToViewIdx, new SizeCallbackForMenu(btnSlide));
    }
   
   

     /**
     * Helper for examples with a HSV that should be scrolled by a menu View's width.
     */
    static class ClickListenerForScrolling implements OnClickListener {
        FacebookSlideView scrollView;
        View menu;
        /**
         * Menu must NOT be out/shown to start with.
         */
        //boolean menuOut = false;

        public ClickListenerForScrolling(FacebookSlideView scrollView, View menu) {
            super();
            this.scrollView = scrollView;
            this.menu = menu;
        }

        @Override
        public void onClick(View v) {
            Context context = menu.getContext();
           
            int menuWidth = menu.getMeasuredWidth();

            // Ensure menu is visible
            menu.setVisibility(View.VISIBLE);

            if (!menuOut) {
                // Scroll to 0 to reveal menu
                Log.d("===slide==","Scroll to right");
                Log.d("===clicked==","clicked");
                int left =20;
                scrollView.smoothScrollTo(left, 0);
            } else {
                // Scroll to menuWidth so menu isn't on screen.
                Log.d("===slide==","Scroll to left");
                Log.d("===clicked==","clicked");
                int left = menuWidth;
                scrollView.smoothScrollTo(left, 0);
            }
            menuOut = !menuOut;
        }
    }

    /**
     * Helper that remembers the width of the 'slide' button, so that the 'slide' button remains in view, even when the menu is
     * showing.
     */
    static class SizeCallbackForMenu implements SizeCallback {
        int btnWidth;
        View btnSlide;

        public SizeCallbackForMenu(View btnSlide) {
            super();
            this.btnSlide = btnSlide;
        }

        @Override
        public void onGlobalLayout() {
            btnWidth = btnSlide.getMeasuredWidth();
            System.out.println("btnWidth=" + btnWidth);
        }

        @Override
        public void getViewSize(int idx, int w, int h, int[] dims) {
            dims[0] = w;
            dims[1] = h;
            final int menuIdx = 0;
            if (idx == menuIdx) {
                dims[0] = w - btnWidth;
            }
        }
    }
   
      
    private void openURL(String url) {
        webView.loadUrl(url);
    }
   
    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
         // TODO Auto-generated method stub
         super.onPageStarted(view, url, favicon);
         loadingFinished = false;
         menuOut = false;
         //mProgress.show();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
             if (!loadingFinished) {
                  redirect = true;
               }

            loadingFinished = false;
            view.loadUrl(url);
            return true;
        }
      
        // when finish loading page
        public void onPageFinished(WebView view, String url) {
            if(!redirect){
                  loadingFinished = true;
               }

               if(loadingFinished && !redirect){
                   if(null !=mProgress) {
                       if(mProgress.isShowing()) {
                            mProgress.dismiss();
                            menuOut = false;
                        }
                    }
                 
               } else{
                  redirect = false;
               }
        }
    }
   
    //scroll the page and open the webview
    private void scrollWebviw(FacebookSlideView scrollView, View menu) {
         Context context = menu.getContext();
        
         int menuWidth = menu.getMeasuredWidth();

         // Ensure menu is visible
         menu.setVisibility(View.VISIBLE);

         if (!menuOut) {
             // Scroll to 0 to reveal menu
             Log.d("===slide==","Scroll to right");
             int left = 0;
             scrollView.smoothScrollTo(left, 0);
         } else {
             // Scroll to menuWidth so menu isn't on screen.
             Log.d("===slide==","Scroll to left");
             int left = menuWidth;
             scrollView.smoothScrollTo(left, 0);
           
         }
         menuOut = false;
    }
   
     
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch(keyCode)
            {
            case KeyEvent.KEYCODE_BACK:
                if(webView.canGoBack() == true){
                        webView.goBack();
                }else if(isWebHistory && webView.canGoBack() == false){
                    isWebHistory = false;
                    Intent menu = new Intent(FacebookSlider.this, FacebookSlider.class);
                    startActivity(menu);
                    webView.clearHistory();
                  
                }else{
                    webView.clearCache(true);
                    moveTaskToBack(true);
                    FacebookSlider.this.finish();
                }
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }
   
       
    @Override
    protected void onResume() {
        super.onResume();
      
    }
}


create FacebookSlideView.class

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;


public class FacebookSlideView extends HorizontalScrollView {
    public FacebookSlideView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

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

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

    void init(Context context) {
        // remove the fading as the HSV looks better without it
        setHorizontalFadingEdgeEnabled(false);
        setVerticalFadingEdgeEnabled(false);
    }

    public void initViews(View[] children, int scrollToViewIdx, SizeCallback sizeCallback) {
        // A ViewGroup MUST be the only child of the HSV
        ViewGroup parent = (ViewGroup) getChildAt(0);

        // Add all the children, but add them invisible so that the layouts are calculated, but you can't see the Views
        for (int i = 0; i < children.length; i++) {
            children[i].setVisibility(View.INVISIBLE);
            parent.addView(children[i]);
        }

        // Add a layout listener to this HSV
        // This listener is responsible for arranging the child views.
        OnGlobalLayoutListener listener = new MyOnGlobalLayoutListener(parent, children, scrollToViewIdx, sizeCallback);
        getViewTreeObserver().addOnGlobalLayoutListener(listener);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Do not allow touch events.
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // Do not allow touch events.
        return false;
    }

    class MyOnGlobalLayoutListener implements OnGlobalLayoutListener {
        ViewGroup parent;
        View[] children;
        int scrollToViewIdx;
        int scrollToViewPos = 0;
        SizeCallback sizeCallback;

        public MyOnGlobalLayoutListener(ViewGroup parent, View[] children, int scrollToViewIdx, SizeCallback sizeCallback) {
            this.parent = parent;
            this.children = children;
            this.scrollToViewIdx = scrollToViewIdx;
            this.sizeCallback = sizeCallback;
        }

        @Override
        public void onGlobalLayout() {
            // System.out.println("onGlobalLayout");

            final HorizontalScrollView me = FacebookSlideView.this;

            // The listener will remove itself as a layout listener to the HSV
            me.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            // Allow the SizeCallback to 'see' the Views before we remove them and re-add them.
            // This lets the SizeCallback prepare View sizes, ahead of calls to SizeCallback.getViewSize().
            sizeCallback.onGlobalLayout();

            parent.removeViewsInLayout(0, children.length);

            final int w = me.getMeasuredWidth();
            final int h = me.getMeasuredHeight();

            // System.out.println("w=" + w + ", h=" + h);

            // Add each view in turn, and apply the width and height returned by the SizeCallback.
            int[] dims = new int[2];
            scrollToViewPos = 0;
            for (int i = 0; i < children.length; i++) {
                sizeCallback.getViewSize(i, w, h, dims);
                // System.out.println("addView w=" + dims[0] + ", h=" + dims[1]);
                children[i].setVisibility(View.VISIBLE);
                parent.addView(children[i], dims[0], dims[1]);
                if (i < scrollToViewIdx) {
                    scrollToViewPos += dims[0];
                }
            }

            // For some reason we need to post this action, rather than call immediately.
            // If we try immediately, it will not scroll.
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    me.scrollBy(scrollToViewPos, 0);
                }
            });
        }
    }

    public interface SizeCallback {
      
        public void onGlobalLayout();

        public void getViewSize(int idx, int w, int h, int[] dims);
    }
}








You can take images from here. 

And give permission in your manifest file <uses-permission android:name="android.permission.INTERNET" />



That's it enjoy coding.

No comments:

Post a Comment

Comments

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...