CodeSnips

Friday, January 21, 2011

Android image drawing

When the emulator is in programming mode (or a program is currently entered/loaded), I wanted to display a magnetic card image in the magnetic card holder slot in the same place it would go on the real HP67.

Problem: how to have the image be invisible when no program is loaded or being entered?

There is a setVisibility() method on the ImageView class, but I'm darned if I could get it to work. So, I adjusted the alpha instead, using the setAlpha() method, and this works beautifully.

Here's how I did it. This works, but right now it uses absolute margin offsets in the RelativeLayout view group. Later, I'm going to investigate how to make this more dynamic to the actual screen dimensions on the device.


  1. Place the card image file in the project's res\drawable folder. In my case, the card file is card.png.
  2. Add a tag to my main.xml layout - which is a RelativeLayout view group. Positioning the image where it should be displayed. The android:src attribute points to the image in the drawable folder. The id is assigned as well so we can get a reference to this view later:

    <RelativeLayout>
    ...
    <ImageView
    android:id="@+id/card"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_width="260dp"
    android:layout_height="50dp"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="87dp"
    android:src="@drawable/card"
    />
    </RelativeLayout>
  3. In the activity class where this view is used, load the view. In my case, I want to have the image be initially invisible, so I set the alpha to zero immediately after setting the content view:

    _vMain = (RelativeLayout) this.getLayoutInflater().inflate(R.layout.main, null);
    setContentView(_vMain);
    ImageView card = (ImageView) findViewById(R.id.card);
    card.setAlpha(0);
  4. Later, when the user clicks the program-mode button, I have logic that reveals the card image like this:

    ImageView card = (ImageView) findViewById(R.id.card);
    card.setAlpha(255);

1 comment: