Thursday, May 28, 2015

Android : Activity with Shared Element Transitions

This post about how to shared the element with transitions between activity . This transition introduced in Lollipop version.

Single Element 


Multiple Element Share



Create Activity with shared elements MainActivity.java

public class MainActivity extends Activity {
  Button secondActBtn;
  ImageView sharedView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        sharedView = (ImageView)findViewById(R.id.imageView1);
        secondActBtn = (Button)findViewById(R.id.button1);
        secondActBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
             //Create Scene Transition
  ActivityOptionsCompat OptionsCompat= ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, sharedView,"shared_image");
  Intent intent = new Intent(MainActivity.this, SecondActivity.class);
      startActivity(intent, OptionsCompat.toBundle());
}
});
    }
}





Create XML activity_main.xml

Set Transition name to View "shared_image"


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#ffffff"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activity 1" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="159dp"
        android:layout_toRightOf="@+id/textView1"
        android:src="@drawable/ic_launcher"
        android:transitionName="shared_image" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="99dp"
        android:text="Second Activity" />

</RelativeLayout>


Then Create Second Activity SecondActivity.java

public class SecondActivity extends Activity{

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


Create XML for second Activity   second_activity.xml

Set transition name to your transition view 

<?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:background="#ffffff"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
         android:transitionName="shared_image"
        android:layout_height="150dp"
        android:src="@drawable/ic_launcher" />

</LinearLayout>


Style should be android:Theme.Material   
styles.xml
<resources>

  <style name="BaseAppTheme" parent="android:Theme.Material">
  <!-- enable window content transitions -->
  <item name="android:windowContentTransitions">true</item>
</style>

</resources>





Share Multiple Element

public class MainActivity extends Activity {
  Button secondActBtn;
  ImageView sharedView,sharedView1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        sharedView = (ImageView)findViewById(R.id.imageView1);
        sharedView1 = (ImageView)findViewById(R.id.imageView2);
        secondActBtn = (Button)findViewById(R.id.button1);
        secondActBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View vd) {
  //Single Element Share
/*  ActivityOptionsCompat OptionsCompat= ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, sharedView,"shared_image");
  Intent intent = new Intent(MainActivity.this, SecondActivity.class);
      startActivity(intent, OptionsCompat.toBundle());*/
//Multi Element Share 
View v = (ImageView)findViewById(R.id.imageView1);
View v2 = (ImageView)findViewById(R.id.imageView2);
Pair<View, String> p1 = Pair.create(v, "shared_image");
Pair<View, String> p2 = Pair.create(v2, "shared_image1");
@SuppressWarnings("unchecked")
ActivityOptionsCompat OptionsCompat= ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, p1,  p2);
  Intent intent = new Intent(MainActivity.this, SecondActivity.class);
      startActivity(intent, OptionsCompat.toBundle());
     
 
}
});
    }

}



Tuesday, May 12, 2015

How to split html string as page in android?

How to split html string as page in android?

This post about how to split html string as page based on device height and width .

In my experiment i want to split the html string in multiple page and i did using javascript.

Step 1:

Create html file assest folder "mypage.html" and copy and paste this HTML code(Its included javascript split function).

Html Code

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
</head>
<body>
<script language="javascript">
  function makeColumns(text, width, height) {
   
    // Array and String prototypes.
    // Internet Explorer 5 didn't have Push, Pop and Shift so here we create them.
    // Split and Join are normally supported by every DHTML capable browser,
    // but they were broken in IE5/MacOSX, madness.
   
    // push appends new elements to an array, and returns the new length
    if (Array.prototype && !Array.prototype.push) {
        Array.prototype.push = function() {
            for (var i = 0; i < arguments.length; i++) this[this.length] = arguments[i];
            return this.length;
        };
    }
   
    // pop removes the last element from an array and returns it
    if (Array.prototype && !Array.prototype.pop) {
        Array.prototype.pop = function() {
            var lastitem = this.length > 0 ? this[this.length - 1] : undefined;
            if (this.length > 0) this.length--;
            return lastitem;
        };
    }
   
    // shift removes the first element from an array and returns it
    if (Array.prototype && !Array.prototype.shift) {
        Array.prototype.shift = function() {
            var firstitem = this.length > 0 ? this[0] : undefined;
            for (var i = 0; i < this.length - 1; i++) this[i] = this[i + 1];
            if (this.length > 0) this.length--;
            return firstitem;
        };
    }
   
    // join returns a string value consisting of all the elements of an array
    // concatenated together and separated by the separator argument
    if (Array.prototype && !Array.prototype.join) {
        Array.prototype.join = function(separator) {
            if (typeof separator != "string") separator = ",";
            var s = "";
            for (var i = 0; i < this.length; i++) {
                if (this[i] != null && this[i] != undefined) s += this[i];
                if (i != this.length - 1) s += separator;
            }
            return s;
        };
    }
   
    // split returns the array that results when a string is separated into substrings
    if (String.prototype && !String.prototype.split) {
        String.prototype.split = function(separator, limit) {
            var s = "" + this;
            var a = new Array();
            var sepIndex;
           
            if (typeof separator != "string") return new Array(s);
            if (separator == "") {
                while (s.length) {
                    a[a.length] = s.substring(0, 1);
                    s = s.substring(1);
                    if (typeof limit == "number" && a.length >= limit) break;
                }
            } else {
                while (s.length) {
                    sepIndex = s.indexOf(separator);
                    a[a.length] = s.substring(0, sepIndex);
                    s = s.substring(sepIndex + separator.length);
                    if (typeof limit == "number" && a.length >= limit) break;
                    if (s.length == 0) a[a.length] = s;
                }
            }
            return a;
        };
    }
   

    if (!document.getElementById("column_sizer")) {
        var _sizer = document.createElement("div");
        _sizer.setAttribute("id", "column_sizer");
        document.getElementsByTagName('body')[0].appendChild(_sizer);
    }
   
    var Columns = {
    singleTags: ["br", "img", "hr", "input", "!--"],
    devmode: "off", // "on" or "off", if set to "on" some info will be displayed in the statusbar.
    cols: new Array(), // Stores the columns during calculations.
    onSplitStart: new Function(),
    onSplitEnd: new Function(),
    onSplit: new Function()
    };
   
   
    // The chop array holds strings that should be removed from the start of every column.
    // Don't remove only one part of a tag pair, like </p>, always remove whole pairs, like <p></p>.
   
    Columns.chop = [
                    '<SPAN class=colbreak></SPAN>',
                    '<span class="colbreak"></span>',
                    '<BR>',
                    '<br>',
                    '<br/>',
                    '<br />',
                    '<p></p>',
                    '<P></P>'
                    ];
   
   
    // Splits a load of text into fragments that will fit in the
    // specified width and height and returns them in an array.
    // It automatically closes unclosed tags and creates opening tags for the following columns.
   
    Columns.splitText = function(text, width, height) {
       
       
       
        var self = this;
       
        self.onSplitStart(text, width, height);
       
        self.cols = new Array();
        self.innerHTMLHits = 0;
        var startDate = new Date();
        var x = "";
       
       
        for (var i = 0; text != ""; i++) {
           
            // put a fitting fragment in cols array and slice it from the text
            self.cols[i] = self.getFragment(text, width, height);
            text = text.slice(self.cols[i].length);
           
            // remove chop strings from the start of the text
            for (var j = 0; j < self.chop.length; j++) {
                if (text.charAt(0) == "\n") {
                    text = text.slice(1);
                }
                x = self.chop[j];
                while (text.indexOf(x) == 0) {
                    text = text.slice(x.length);
                }
            }
           
            // add tags from opentags array
            for (var k = self.openTags.length - 1; k >= 0; k--) {
                self.cols[i] += "</" + self.openTags[k].split(" ")[0] + ">";
                if (text != "") text = "<" + self.openTags[k] + ">" + text;
            }
           
            // remove chop strings from the start of the text again
            for (var m = 0; m < self.chop.length; m++) {
                if (text.charAt(0) == "\n") text = text.slice(1);
                x = self.chop[m];
                while (text.indexOf(x) == 0) text = text.slice(x.length);
            }
           
            // fire onSplit event
            self.onSplit(self.cols[i]);
        }
       
        if (self.devmode == "on") {
            var endDate = new Date();
            var message = "Time taken for splitting text = " + (endDate - startDate) / 1000 + " seconds";
            message += " Number of unclosed tags found = " + self.openTags.length;
            message += " innerHTMLHits = " + self.innerHTMLHits;
            defaultStatus = message;
            console.log(defaultStatus);
        }
       
       
         
        self.onSplitEnd(self.cols);
      
          console.log( self.cols);
          var message1 = self.cols;
            AndroidFunction.showsplitData(self.cols);
        //  document.getElementById("column_sizer").innerHTML = self.cols;
        document.getElementById("column_sizer").innerHTML="";
        return self.cols;
       
       
    };
   
   
    Columns.getFragment = function(text, width, height) {
        var objSizer = document.getElementById("column_sizer");
        objSizer.style.width = width + "px";
       
        var i = 0;
        var limit = 0;
        var add = 0;
        var doloop = false;
        this.openTags = new Array();
       
        objSizer.innerHTML = text;
        //debugger;
       
        if (objSizer.offsetHeight <= height) {
            i = text.length;
        } else {
            doloop = true;
            limit = text.length;
        }
       
       
        // This loop determines the raw piece of text that fits in the specified width and height.
        // It is the most powerhungry part of the script because of the repeated innerHTML manipulation.
        // It uses a binary search between 0 and text.length.
        while (doloop) {
           
            add = Math.round((limit - i) / 2);
           
            if (add <= 1) {
                doloop = false;
            }
            if (this.innerHTMLHits > 1000) {
                this.innerHTMLHits = 0;
                doloop = false;
                console.log('too many operations: columns cannot be created');
                //break;
                return;
            } else {
                i += add;
                objSizer.innerHTML = text.substr(0, i);
                //debugger;
                if (objSizer.offsetHeight > height) {
                    limit = i;
                    i -= add;
                }
                this.innerHTMLHits++;
            }
           
        }
       
       
        // Making sure there are no broken words or tags like "<img" at the end of this fragment.
        // This also ensures there will be no broken words or tags at the start of the next fragment.
        if (text.substr(0, i) != text) {
            var lastSpace = text.substr(0, i).lastIndexOf(" ");
            var lastNewline = text.substr(0, i).lastIndexOf("\n");
            var lastGreater = text.substr(0, i).lastIndexOf(">");
            var lastLess = text.substr(0, i).lastIndexOf("<");
            if (lastLess <= lastGreater && lastNewline == i - 1) i = i;
            else if (lastSpace != -1 && lastSpace > lastGreater && lastGreater > lastLess) i = lastSpace + 1;
            else if (lastLess > lastGreater) i = lastLess;
            else if (lastGreater != -1) i = lastGreater + 1;
        }
       
       
        // Doing the column breaks.
        text = text.substr(0, i).split('<SPAN class=colbreak></SPAN>')[0];
        text = text.substr(0, i).split('<span class="colbreak"></span>')[0];
       
       
        // Seeking unclosed tag pairs in this fragment and storing them in the openTags array.
        var doPush = true;
        var tags = text.split("<");
        tags.shift();
       
        for (var j = 0; j < tags.length; j++) {
            // Splitting at ">" and taking the first item.
            // Now we have the whole tag with its attributes and without "<" and ">".
            tags[j] = tags[j].split(">")[0];
           
            // If it's a selfclosing xhtml or xml tag there's no need to do anything with it.
            if (tags[j].charAt(tags[j].length - 1) == "/") continue;
           
            if (tags[j].charAt(0) != "/") {
                for (var k = 0; k < this.singleTags.length; k++) {
                    if (tags[j].split(" ")[0].toLowerCase() == this.singleTags[k]) doPush = false;
                }
                if (doPush) this.openTags.push(tags[j]);
                doPush = true;
            } else this.openTags.pop();
        }
       
        return text;
    };
 
   
    return Columns.splitText(text, width, height);
   
}


  
  
</script>

</body>

</html>



Activity Code


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AndroidHTMLActivity extends Activity {

 WebView myBrowser;
 EditText Msg;
 Button btnSendMsg;

 /***
  * VIJAYAKUMAR M
  */

 /** Called when the activity is first created. */
   @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
   @JavascriptInterface
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       myBrowser = (WebView)findViewById(R.id.mybrowser);
     
       final MyJavaScriptInterface myJavaScriptInterface
        = new MyJavaScriptInterface(this);
       myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
     
       myBrowser.getSettings().setJavaScriptEnabled(true);
       myBrowser.loadUrl("file:///android_asset/mypage.html");
     
       Msg = (EditText)findViewById(R.id.msg);
    btnSendMsg = (Button)findViewById(R.id.sendmsg);
    myBrowser.setWebViewClient(new WebViewClient() { 
    @Override 
    public void onPageFinished(WebView view, String url) 
    { 
    String jscontent = "<div class='Content'>"
        +"<p style='color:red'>How to split html string as page in android?<br></p>"
        +"<u><p>This post about how to split html string as page based on device height and width .In my experiment i want to split the html string in multiple page and i did using javascript.</p></u>"
        +"<u><p>This post about how to split html string as page based on device height and width .In my experiment i want to split the html string in multiple page and i did using javascript.</p></u>"
        +"<p style='color:red'>This post about how to split html string as page based on device height and width .In my experiment i want to split the html string in multiple page and i did using javascript.<br></p>"
        +"<p style='color:red'>This post about how to split html string as page based on device height and width .In my experiment i want to split the html string in multiple page and i did using javascript.<br></p>"
      +"</div>";
      myBrowser.loadUrl("javascript:makeColumns(\""+jscontent+"\" , "+"100"+" , "+"100"+")");
    // String str=   "javascript:makeColumns(\""+jscontent+"\" , "+"100"+" , "+"100"+")";
    
  
  
    }});
 
   }
 
 public class MyJavaScriptInterface {
  Context mContext;

     MyJavaScriptInterface(Context c) {
         mContext = c;
     }
     @JavascriptInterface
     public void showsplitData(String[] splitData){
    
      for(int i =0; i<splitData.length; i++){
     
      Log.e("AN", "Split Html Data :: " +splitData[i]);
      }
     
     
     }
   
     public void openAndroidDialog(){
   
     }

 }

}




XML Code mainactivity.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView
   android:layout_width="fill_parent"
     android:visibility="gone"
   android:layout_height="wrap_content"
   android:text="Helloo"
   />
<EditText
   android:id="@+id/msg"
   android:layout_width="fill_parent"
     android:visibility="gone"
   android:layout_height="wrap_content" />
<Button
 android:id="@+id/sendmsg"
   android:layout_width="fill_parent"
   android:visibility="gone"
   android:layout_height="wrap_content"
   android:text="Msg to JavaScript"
   />
<WebView
   android:id="@+id/mybrowser"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
  />
</LinearLayout>



Input 
        String jscontent = "<div class='Content'>"
                      +"<p style='color:red'>How to split html string as page in android?<br></p>"
                      +"<u><p>This post about how to split html string as page based on device height and width .In my experiment i want to split the html string in multiple page and i did using javascript.</p></u>"
                      +"<u><p>This post about how to split html string as page based on device height and width .In my experiment i want to split the html string in multiple page and i did using javascript.</p></u>"
                      +"<p style='color:red'>This post about how to split html string as page based on device height and width .In my experiment i want to split the html string in multiple page and i did using javascript.<br></p>"
                      +"<p style='color:red'>This post about how to split html string as page based on device height and width .In my experiment i want to split the html string in multiple page and i did using javascript.<br></p>"

                    +"</div>";


Output 


        <div class='Content'><p style='color:red'>How to split html string as page in android?<br></p></div>
        
<div class='Content'><u><p>This post about how to split html string as page based </p></u></div>
       
  <div class='Content'><u><p>on device height and width .In my experiment i want to split </p></u></div>

         <div class='Content'><u><p>the html string in multiple page and i did using </p></u></div>

         <div class='Content'><u><p>javascript.</p></u><u><p>This post about how to split html </p></u></div>

         <div class='Content'><u><p>string as page based on device height and width .In my </p></u></div>

        <div class='Content'><u><p>experiment i want to split the html string in multiple page </p></u></div>
         <div class='Content'><u><p>and i did using javascript.</p></u><p style='color:red'>This post </p></div>
        <div class='Content'><p style='color:red'>about how to split html string as page based on device </p></div>
         <div class='Content'><p style='color:red'>height and width .In my experiment i want to split the html </p></div>

         <div class='Content'><p style='color:red'>string in multiple page and i did using javascript.<br></p><p style='color:red'></p></div>


Check out this may be help you

Related Posts Plugin for WordPress, Blogger...