Sunday, August 21, 2016

(Android) Simple tablayout hacky trick to custom text, background and etc

alt tag 

alt tag 


Above images is where is tried to custom the tablayout to become the shape like that :D The designer design the UI like that and i have to came out a solution to custom it..
Note: I create it by my own. If you have better solution, you can suggest me :D TQ..

Below is the base init to custom tab layout
        Tablayout tabs = (TabLayout)findViewById(R.id.tabs);
        //cast the selected tablayout to viewgroup
        ViewGroup vg = (ViewGroup) tabs.getChildAt(0);
        //count how many tabs in tablayout
        int tabsCount = vg.getChildCount();
        //iterative each tab
        for (int j = 0; j < tabsCount; j++) {
            //Get all element in each tabs and cast to viewgroup
            ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
            //count the element in each tabs
            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                // cast to View
                View tabViewChild = vgTab.getChildAt(i);
            }
        }

How to use
To change the font of the tabs. Just use View instanceOf TextView
        // using built-in tablayout function to change indicator and text color but limited
        tabs.setTabTextColors(ContextCompat.getColor(this, R.color.md_grey_500), ContextCompat.getColor(this, R.color.white));
        tabs.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.transparent));

Custom Tabs
        // init your font
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/knockout-htf49-liteweight.ttf");
        ViewGroup vg = (ViewGroup) tabs.getChildAt(0);
        int tabsCount = vg.getChildCount();
        for (int j = 0; j < tabsCount; j++) {
            ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                View tabViewChild = vgTab.getChildAt(i);
                // Get TextView Element
                if (tabViewChild instanceof TextView) {
                  // change font
                  ((TextView) tabViewChild).setTypeface(tf);
                  // change color
                  ((TextView) tabViewChild).setTextColor(getResources().getColor(R.color.white));
                  // change size
                  ((TextView) tabViewChild).setTextSize(18);
                  // change padding
                  tabViewChild.setPadding(0, 0, 0, 0);
                  //..... etc...
                }
            }
        }

To change background of the tabs
        ViewGroup vg = (ViewGroup) tabs.getChildAt(0);
        int tabsCount = vg.getChildCount();
        for (int j = 0; j < tabsCount; j++) {
            View view = vg.getChildAt(j);
            //change drawable for each tabs
            view.setBackgroundResource(R.drawable.backgroundtabs);

            //if you want to diff drawable for each tabs for example tabs is 4
            //if j == 0    view.setBackgroundResource(R.drawable.backgroundtabs1);  
            //if j == 1    view.setBackgroundResource(R.drawable.backgroundtabs2);
            //if j == 2    view.setBackgroundResource(R.drawable.backgroundtabs3);
            //if j == 3    view.setBackgroundResource(R.drawable.backgroundtabs4);

            ViewGroup vgTab = (ViewGroup) view;
            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                View tabViewChild = vgTab.getChildAt(i);
            }
        }

Add listener if you want to track the tab changes
tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // code what happen when tab is selected  
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // code what happen when tab is unselected
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // code what happen when the tab is reselected
            }
        });

To change background of the tablayout
        <android.support.design.widget.TabLayout
          android:layout_height="wrap_content"
          android:layout_width="match_parent"
          android:id="@+id/tabs"
          android:background="@drawable/stripetab"    <-- create stripe background like example image
          app:tabTextAppearance="@style/CustomTabStyle"/>

NOTES
if you want to use scrollable mode ...etc, You need to set the tabs size (i dont know why). If not, it will looks ugly
My case: i hardcode the width to 120dp (you can change it or just calculate by your own for your perfect size)
       int width = 120; // width - width of tabs 
       int tabsize = 120 * tabcount; // tabcount - number of tabs
       ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
       if (sizeScreen() < tabsize) 
           vgTab.getLayoutParams().width = dpToPx(120);

       public int dpToPx(int dp) {
           DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
           return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
       }

       public int sizeScreen(){
           return (int)((Resources.getSystem().getDisplayMetrics().widthPixels)/ Resources.getSystem().getDisplayMetrics().density);
       }


This is example of what im doing
    private void setupTabLayout(final TabLayout tabs) {
        tabs.setTabTextColors(ContextCompat.getColor(this, R.color.md_grey_500), ContextCompat.getColor(this, R.color.white));
        tabs.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.transparent));

        if (sizeScreen()<tabsize){
            tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
            tabs.setTabGravity(TabLayout.GRAVITY_FILL);
        }
        else{
            tabs.setTabMode(TabLayout.MODE_FIXED);
            tabs.setTabGravity(TabLayout.GRAVITY_FILL);
        }

        // CHANGE TAB TEXT FONT
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/knockout-htf49-liteweight.ttf");
        ViewGroup vg = (ViewGroup) tabs.getChildAt(0);
        int tabsCount = vg.getChildCount();
        for (int j = 0; j < tabsCount; j++) {
            ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);

            if (j==0){
                View view = vg.getChildAt(j);
                view.setBackgroundResource(R.drawable.backgroundtabs);
            }

            if (sizeScreen()<tabsize) {
                vgTab.getLayoutParams().width = dpToPx(120);
            }

            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                View tabViewChild = vgTab.getChildAt(i);
                if (tabViewChild instanceof TextView) {
                    ((TextView) tabViewChild).setTypeface(tf);
                    ((TextView) tabViewChild).setTextSize(18);
                    ((TextView) tabViewChild).setAllCaps(true);
                    ((TextView) tabViewChild).setSingleLine(true);
                    //set the text to marquee if text longer than tabs size
                    ((TextView) tabViewChild).setEllipsize(TextUtils.TruncateAt.MARQUEE);
                    ((TextView) tabViewChild).setMarqueeRepeatLimit(100);
                    if (j==0){
                        tabViewChild.setPadding(0, 0, 0, 0);
                    }
                    else {
                        tabViewChild.setPadding(0, padding, 0, 0);
                    }
                }
            }
        }

        // add listener when tab is change
        tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            ViewGroup vg = (ViewGroup) tabs.getChildAt(0);

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ViewGroup vgTab = (ViewGroup) vg.getChildAt(tab.getPosition());
                if (tab.getPosition()==0)
                    vg.getChildAt(tab.getPosition()).setBackgroundResource(R.drawable.backgroundtabs);

                else if (tab.getPosition()==tabcount-1)
                    vg.getChildAt(tab.getPosition()).setBackgroundResource(R.drawable.backgroundtabs_last);

                else
                    vg.getChildAt(tab.getPosition()).setBackgroundResource(R.drawable.backgroundtabs_middle);

                int tabChildsCount = vgTab.getChildCount();
                for (int i = 0; i < tabChildsCount; i++) {
                    View tabViewChild = vgTab.getChildAt(i);
                    if (tabViewChild instanceof TextView) {
                        tabViewChild.setPadding(0, 0, 0, 0);
                    }
                }
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                ViewGroup vgTab = (ViewGroup) vg.getChildAt(tab.getPosition());
                vg.getChildAt(tab.getPosition()).setBackgroundResource(0);
                int tabChildsCount = vgTab.getChildCount();
                for (int i = 0; i < tabChildsCount; i++) {
                    View tabViewChild = vgTab.getChildAt(i);
                    if (tabViewChild instanceof TextView) {
                        tabViewChild.setPadding(0, padding, 0, 0);
                    }
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

Sunday, August 14, 2016

PROMED@CS 2012 Question 9 (Inseparable Luq & Ruq)

Download Question Here

Change Snippet Background Color
          
import java.io.*;
import java.util.*;

/**
 * Created by Hafiq Iqmal on 14/8/2016.
 * PROMED CS 2012
 * Using bruteforce closest pairing coordinate and Divide and Conquer
 */

public class InseparableLR {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String line = System.getProperty("line.separator");
        scan.useDelimiter(line);

        int cases = scan.nextInt();
        String[] ans = new String[cases];

        for (int x = 0; x < cases; x++) {
            int num = scan.nextInt();
            List <Coordinate> points = new ArrayList <> ();

            for (int input = 0; input < num; input++) {
                String[] item = scan.next().split(" ");
                points.add(new Coordinate(input + 1, Double.parseDouble(item[0]), Double.parseDouble(item[1]), item[2].charAt(0)));
            }

            CoordinateDetail db = bruteForce(points);
            // CoordinateDetail db = divideAndConquer(points);

            ans[x] = "Case #" + (x + 1) + ": " + db.toString();
        }

        for (int x = 0; x < cases; x++) {
            System.out.println(ans[x]);
        }
    }


    private static class Coordinate {
        private int id;
        private double x;
        private double y;
        private char code;

        public Coordinate(int id, double x, double y, char code) {
            this.id = id;
            this.x = x;
            this.y = y;
            this.code = code;
        }

        public int getId() {
            return id;
        }

        public double getX() {
            return x;
        }

        public double getY() {
            return y;
        }

        public char getCode() {
            return code;
        }

        public String toString() {
            return "(" + x + ", " + y + " , " + code + ")";
        }
    }

    private static class CoordinateDetail {
        private Coordinate point1 = null;
        private Coordinate point2 = null;
        private double distance = 0.0;

        public CoordinateDetail(Coordinate point1, Coordinate point2, double distance) {
            this.point1 = point1;
            this.point2 = point2;
            this.distance = distance;
        }

        public Coordinate getPoint1() {
            return point1;
        }

        public Coordinate getPoint2() {
            return point2;
        }


        public double getDistance() {
            return distance;
        }


        public void set(Coordinate point1, Coordinate point2, double distance) {
            this.point1 = point1;
            this.point2 = point2;
            this.distance = distance;
        }

        public String toString() {
            if (Character.toLowerCase(point1.getCode()) > Character.toLowerCase(point2.getCode()))
                return point2.getId() + " " + point2.getCode() + " " + point1.getId() + " " + point1.getCode();
            else if (Character.toLowerCase(point1.getCode()) < Character.toLowerCase(point2.getCode()))
                return point1.getId() + " " + point1.getCode() + " " + point2.getId() + " " + point2.getCode();


            return "NO SOLUTION";

        }
    }

    private static double calDistance(Coordinate p1, Coordinate p2) {
        double xdist = p2.getX() - p1.getX();
        double ydist = p2.getY() - p1.getY();
        return Math.hypot(xdist, ydist);
    }

    // much faster than DnV for list of Coordinate is less than 100
    private static CoordinateDetail bruteForce(List <Coordinate> points) {
        int coorSize = points.size();
        if (coorSize < 2)
            return null;

        CoordinateDetail coorPoint = new CoordinateDetail(points.get(0), points.get(1), calDistance(points.get(0), points.get(1)));
        if (coorSize > 2) {
            for (int i = 0; i < coorSize - 1; i++) {
                Coordinate point1 = points.get(i);
                for (int j = i + 1; j < coorSize; j++) {
                    Coordinate point2 = points.get(j);
                    if(point1.getCode() != point2.getCode()){
                        double distance = calDistance(point1, point2);
                        if (distance < coorPoint.getDistance())
                            coorPoint.set(point1, point2, distance);
                    }
                }
            }
        }
        return coorPoint;
    }
}
          
        

PROMED@CS 2012 Question 8 (Word Structure)

Download Question Here

Change Snippet Background Color
          
import java.io.*;
import java.util.*;

/**
 * Created by Hafiq Iqmal on 14/8/2016.
 * PROMED CS 2012
 */

public class StructureWord{
   public static void main(String[] args){
      Scanner scan = new Scanner(System.in);
      String line = System.getProperty("line.separator");
      scan.useDelimiter(line);
      
      int cases = scan.nextInt();
      String [] ans = new String[cases];
      
      for(int x=0;x<cases;x++){
         String[] word = scan.next().split("\\s+");
         String a = getStructure(word[0]);
         String b = getStructure(word[1]);
         if(a.equals(b)){
            ans[x] = "Case #"+(x+1)+": same";
         }
         else{
            ans[x] = "Case #"+(x+1)+": different";

         }
      }
      
      for(int x=0;x<cases;x++){
         System.out.println(ans[x]);
      }
   }
   
   private static String getStructure(String word){
      String v = "aeiouAEIOU";
      String s = "";
      for(int x=0;x<word.length();x++){
         if(v.contains(word.charAt(x)+"")){
            s +="v";
         }
         else{
            s +="c";
         }
      }
      
      return s;
   }
}
          
        

PROMED@CS 2012 Question 7 (LegoLand Ticket)

Download Question Here

Change Snippet Background Color
          
import java.util.*;
import java.io.*;
import java.text.*;

/**
 * Created by Hafiq Iqmal on 14/8/2016.
 * PROMED CS 2012
 */

public class LegoLandTicket{
   public static void main(String[] args){
      Scanner scan = new Scanner(System.in);
      String line = System.getProperty("line.separator");
      scan.useDelimiter(line);
   
      int cases = scan.nextInt();
      String [] ans = new String[cases];
      
      DecimalFormat df = new DecimalFormat("RM0.00");
      
      for(int x=0;x<ans.length;x++){
         String[] split = scan.next().trim().split(" ");
         int [] org = new int[split.length];
         for(int bil=0;bil<split.length;bil++){
            org[bil] = Integer.parseInt(split[bil]);
         }
         
         float child = 0,adult = 0, senior=0;
         int c=0,a=0,s=0;
         
         for(int y=1;y<=org[0];y++){
            if(org[y]>=3 && org[y]<=11){
               child+= 110;
               c++;
            }
            else if(org[y]>=12 && org[y]<=59){
               adult += 140;
               a++;
            }
            else if(org[y]>=60){
               senior += 110;
               s++;
            }
         }
         
         int voucher = org[org.length-1];
         float pv = 0;
         if(a>=c){
            if(voucher>=c){
               pv = c * 110;
            }
            else{
               pv = voucher * 110;   
            }
         }
         else{
            pv = a * 110;
         }
         
         ans[x] = "Cases #"+(x+1)+": "+df.format((adult+child+senior) - pv);
      }
      
      for(int x=0;x<cases;x++){
         System.out.println(ans[x]);
      }
   }
}
          
        

PROMED@CS 2012 Question 6 (Even Or Odd Wins!)

Download Question Here

Change Snippet Background Color
          
            
          

import java.util.*;
import java.io.*;
import java.math.*;

/**
 * Created by Hafiq Iqmal on 14/8/2016.
 * PROMED CS 2012
 */

public class EvenOrOdd{
   public static void main(String[] args){
      Scanner scan = new Scanner(System.in);
      String line = System.getProperty("line.separator");
      scan.useDelimiter(line);
      
      int cases = scan.nextInt();
      String [] ans = new String[cases];
      
      for(int x=0;x<cases;x++){
         int num = scan.nextInt();
         
         int cube = num * num * num;
         boolean even = false;
         boolean odd = false;
         
         while(cube > 0){
            if(((cube % 10) % 2 == 0)){
               even = true;
            }
            else{
               odd = true;
            }
            
            cube /= 10;            
         }
         
                  
         if(even && !odd){
            ans[x] = "Case #"+(x+1)+": EVEN";
         }
         else if(!even && odd){
            ans[x] = "Case #"+(x+1)+": ODD";
         }
         else{
            ans[x] = "Case #"+(x+1)+": MIXED";
         }
      }
      
      for(int x=0;x<cases;x++){
         System.out.println(ans[x]);
      }
   }
}

        

PROMED@CS 2012 Question 5 (Dash Pattern)

Download Question Here

Change Snippet Background Color
          
import java.util.*;
import java.io.*;

/**
 * Created by Hafiq Iqmal on 14/8/2016.
 * PROMED CS 2012
 */

public class DashPattern{

   public static void main(String[] args){
      Scanner scan = new Scanner(System.in);
      String line = System.getProperty("line.separator");
      scan.useDelimiter(line);
   
      int cases = scan.nextInt();
      String [] ans = new String[cases];
      
      for(int x=0;x<cases;x++){
         String[] split = scan.next().split("\\s+");
         
         String tiang = "|";
         String draw = "";
         
         int[] num = new int[split.length];
         
         for(int z=0;z<split.length;z++){
            num[z] = Integer.parseInt(split[z]);
         }
         
         int len = num[0];
         
         int current = 0;
         boolean selang = true;
         
         while(current < len){
            for(int y=1;y<num.length;y++){
                  for(int index=0;index<num[y];index++){
                     if (current < len){
                        if(y%2 == 1)
                           draw += "_";
                        else
                           draw += " ";
                     }
                     else{
                        break;
                     }
                     current ++;
                  }
                                
               selang = (selang)?false:true;
            }
         }
         
         ans[x] = "Case #"+(x+1)+": "+tiang+draw+tiang;
      }
      
      for(int x=0;x<cases;x++){
         System.out.println(ans[x]);
      }
      
   }

}
          
        

PROMED@CS 2012 Question 4 (Hail Taxi)

Download Question Here

Change Snippet Background Color

import java.util.*;
import java.io.*;

/**
 * Created by Hafiq Iqmal on 14/8/2016.
 * PROMED CS 2012
 * Using bruteforce closest pairing coordinate
 */

public class HailTaxi {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String line = System.getProperty("line.separator");
        scan.useDelimiter(line);

        int cases = scan.nextInt();
        String[] ans = new String[cases];

        for (int x = 0; x < cases; x++) {
            List <Coordinate> list = new ArrayList <>();
            String[] p = scan.next().trim().split(" ");
            
            Coordinate player = new Coordinate(Double.parseDouble(p[0]), Double.parseDouble( p[1]));
            
            while (true) {
                String input = scan.next().trim();
                if (input.equals("10001 10001"))
                    break;
                else {
                    String[] in = input.split(" ");
                    list.add(new Coordinate(Double.parseDouble(in[0]), Double.parseDouble(in[1])));
                }
            }
            
            list.add(new Coordinate(0,0));
            Collections.sort(list);
                        
            Coordinate bf = findNearest(list,player);

            ans[x] = "Case #" + (x + 1) + ": " + bf;
        }

        for (int x = 0; x < cases; x++) {
            System.out.println(ans[x]);
        }
    }

    private static class Coordinate implements Comparable<Coordinate> {
        private double x;
        private double y;

        public Coordinate(double x, double y) {
            this.x = x;
            this.y = y;
        }

        public double getX() {
            return x;
        }

        public double getY() {
            return y;
        }
        
        @Override
        public int compareTo(Coordinate p){
            if(y - p.y != 0){
                return (int)(y - p.y);
            }
 
            if(x - p.x != 0){
                return (int)(x - p.x);
            }
 
            return 0;
        }

        public String toString() {
            return (int)x + " " + (int)y;
        }
    }

 
    private static double calDistance(Coordinate a,Coordinate p){
        return (a.getX()-p.getX())*(a.getX()-p.getX()) + (a.getY()-p.getY())*(a.getY()-p.getY());
    }

    private static Coordinate findNearest(List <Coordinate> points, Coordinate player) {        
        Coordinate closest = points.get(0);
        for (Coordinate coor:points) {            
            if (calDistance(coor,player) <= calDistance(closest, player))
               closest = coor;
        }
        
        return closest;
    }
   
}