Skip to main content

Android: Get the size of a custom view before display.

When developing applications or simple games for Android where you are drawing or writing to a view, an issue arises upon startup of the view. In my case I had a game where I wanted to calculate screen tile size before the game view starts, but with most tutorials I had seen everything happened after the view was fully running. That turned into a chicken and the egg scenario. I needed some key information before I could start the game view, but the default techniques didn’t allow for that.

https://www.youtube.com/watch?v=TkjWTUFW5UY

Here is the code on GitHub for this article.

I was able to get around the issue with a few techniques.

  • Have my main Activity linked with an xml layout file that has two empty nested linear layouts that fill the screen.
  • Make a custom view that houses the main draw code. For this example, all I do is fill the screen with black and display the available screen size.
  • Attach a ViewTreeObserver.OnGlobalLayoutListener in the Activity that will be the boot code upon getting the screen’s view size.

I’m not showing everything here. Look at the project on GitHub for that.

The main activity:

public class ActivityMain extends Activity {


    LinearLayout mLinearLayout;
    ViewMain mainView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the main layout to our XML file with empty layouts
        setContentView(R.layout.activity_activity_main);

        // Get a reference to the interior layout we want to draw on
        mLinearLayout = (LinearLayout) findViewById(R.id.layoutlinearmain);

        // Instantiate our custom view
        mainView = new ViewMain(this);

        // Clean up the layout if needed and push our custom view into it
        mLinearLayout.removeAllViews();
        mLinearLayout.addView(mainView);

        // Once the view is ready, the layout listener will be called
        mLinearLayout.getViewTreeObserver().addOnGlobalLayoutListener(mainViewLayoutListener);
    }

    /**
     * This is used so we can get screen size before everything is finished loading
     * and visible on the screen
     */
    ViewTreeObserver.OnGlobalLayoutListener mainViewLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @SuppressWarnings("deprecation")
        @SuppressLint("NewApi")
        @Override
        public void onGlobalLayout() {
            ViewTreeObserver obs = mLinearLayout.getViewTreeObserver();

            // Deal with the view tree differently based on Android SDK version
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                obs.removeOnGlobalLayoutListener(this);
            } else {
                obs.removeGlobalOnLayoutListener(this);
            }

            // Save what will be the full screen size
            // Finish the view startup process now that we know the size
            mainView.initialize(new Point(mLinearLayout.getWidth(), mLinearLayout.getHeight()));
        }
    };
}

The custom view:


public class ViewMain extends View {

    Paint textPaint = new Paint();
    Rect messageBounds = new Rect();
    Path lineText = new Path();
    String viewWidthMessage = "";
    String viewHeightMessage = "";

    public ViewMain(Context parentActivityContext) {
        super(parentActivityContext);
    }

    /**
     * This function is called by the parent activity once screen bounds are calculated
     * This is where all code to initialize something like a game would go
     */
    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public void initialize(Point screenBounds) {
        viewWidthMessage = "View Width: " + String.valueOf(screenBounds.x);
        viewHeightMessage = "View Height: " + String.valueOf(screenBounds.y);

        // Make a paint instance that will be used when drawing text
        textPaint.setColor(Color.GREEN);
        textPaint.setAntiAlias(true);
        textPaint.setSubpixelText(true);
        textPaint.setTextSize((float) screenBounds.x / 30f);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        // Fill the entire view with black as a base color
        canvas.drawColor(Color.BLACK);

        // Draw text on the view
        // Get the size of the first line of text we will display on screen
        textPaint.getTextBounds(viewWidthMessage, 0, viewWidthMessage.length(), messageBounds);
        int xPosition = 1;
        int yPosition = 1;
        int currentLineHeight = yPosition + messageBounds.height() * 2;

        lineText.moveTo(xPosition, currentLineHeight);
        lineText.lineTo(xPosition + messageBounds.width(), currentLineHeight);
        canvas.drawTextOnPath(viewWidthMessage, lineText, 0, 0, textPaint);
        lineText.reset();

        currentLineHeight += messageBounds.height() * 2;
        lineText.moveTo(xPosition, currentLineHeight);
        textPaint.getTextBounds(viewHeightMessage, 0, viewHeightMessage.length(), messageBounds);
        lineText.lineTo(xPosition + messageBounds.width(), currentLineHeight);
        canvas.drawTextOnPath(viewHeightMessage, lineText, 0, 0, textPaint);
    }
}

The main Activity’s XML:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layoutlinearmaintopcontainer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true">

    <LinearLayout
        android:id="@+id/layoutlinearmain"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">
        <!-- this is where the draw screen will be added programmatically -->
    </LinearLayout>

</LinearLayout>



Popular posts from this blog

ChatGPT is a new, and faster, way to do programming!

Currently ChatGPT is in a free “initial research preview” . One of its well known use cases at this point is generating software code. I’ve also just used it to write most of this article… Well, actually a future article about cleaning up SRT subtitle files of their metadata faster than I have been by hand with Notepad++ and its replace functionality. Update: I recorded a screencast of writing the SRT subtitle cleaner application loading and processing portion. I relied heavily on ChatGPT for code. It was a fun process! https://youtu.be/TkEW39OloUA ChatGPT, developed by OpenAI, is a powerful language model that can assist developers in a variety of tasks, including natural language processing and text generation. One such task that ChatGPT can help with is creating an SRT cleaner program. SRT, or SubRip Subtitle, files are commonly used to add subtitles to video files. However, these files can become cluttered with unnecessary information, such as timing lines or blank spaces. To clean...

Theme error in 2010s Android App after AppCompat Migration

I plan on releasing a lot of my old work as GPL open source, but most of it has aged to the point that it no longer functions, or if it does work it’s running in compatibility mode. Basically it’s no longer best practices. Not a good way to start off any new public GPL projects, in my opinion. The current project I’m working on is an Android app that calculates star trails meant to help photographers get or avoid that in their night time photos. For now I’m going to skip some of the import process because I didn’t document it exactly. It’s been mostly trial and error as I poke around Android Studio post import. The Android Studio import process… Removing Admob Google Play code before the project would run at all. After removing dependencies, it kind of worked, but when running it in the emulator it shows a pop-up message saying that the app was developed for an old version of Android. Going through the process of updating code to match current best practices… I had the IDE convert the ...

Printing to file in Linux WINE

I noticed that this post has been sitting as a draft since 2011. At this point I have no idea if it’s useful or what I was even doing, but I might as well make it public in case someone can find it helpful! So I’ve been trying to get one of those PDF print drivers working in WINE without success. I then came upon a process that might work. When printing you need to select the checkbox “Print to file” that creates a .prn file. Just Linux things... I was using a program that only has printing facilities, but I want to export around 100 pages of text and images. Once you have the .prn (postscript) file, you can do any number of things to it. In my case I want the postscript file to be converted to HTML. I am also considering PDF format because that has more conversion options to eventually get me to HTML or plain text. sudo apt-get install cups-pdf Or it looks like that package might have changed to this… sudo apt-get install printer-driver-cups-pdf Where PDFs would be generated in /home/...