Home » Android » android – How to create a layout that's split diagonally and the two halves are clickable?

android – How to create a layout that's split diagonally and the two halves are clickable?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need to create a layout that’s split the screen diagonally into two parts with different colors as their background.Something like this:

enter image description here

How can I achieve this?

How to&Answers:

This can be done as follows:

  • Create a FrameLayout (lets say 50×50 pixels).
  • Create two ImageViews (inside the FrameLayout and set them to match_parent) and as source give them the two triangles.
  • Create an onTouchListener for the FrameLayout.

Now comes the tricky part:

public boolean onTouch(View v, MotionEvent me){ 
  float time  = System.getCurrentTimeInMilles();

  if(me.action == MotionEvent.DOWN)
    lastTimePress = time;   /// global var

  if(me.action == MotionEvent.UP && lastTimePress - time < 200){
    if(calcPlace(me.getX()) < me.getY())
      /// go to onClick for the right triangle
    else
      /// go to onClick for the left triangle
  }
}

public int calcPlace(int x){
  return 50 -x; 
}

You don’t have to set onClickListener for the two triangles (ImageViews), just have a method that handles the clicks.

Some fields might be wrong, sorry about it 🙂 I hope you get the point.

Answer:

It should be possible to create a View as the background, then put another one above it with a 45 degree angle. Put both inside a FrameLayout to clip it to a rect again. You may assign a onClick handler to each of them.

Answer:

You can set the background by xml. Make the abc image of the same background in a different size:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/abc"
        android:orientation="vertical" >
</LinearLayout>