Get text value

Former Member
Former Member
How I can get text value in code from label?
  • Are you asking about using strings as resources?
  • Former Member
    Former Member over 8 years ago
    no, I asking about getting values in runtime
  • There is no accessor for the text of a Ui.Text (the class that encapsulates a label that is described in a layout[/i]). If you want to be able to access that data, you have two options.

    • Maintain a variable (theString in this example) that you can read/write as necessary, and call label.setText(theString) any time theString changes. Since MonkeyC uses reference counted objects, this should not be costly in terms of memory used, and the cost to assign the references is super low.
    • Write your own class (possibly derived from Ui.Text) that provides an accessor for the value. This is really a tweak on the previous option, but it does require you to modify the layout (if you're using them).


    The second option would look something like this (I haven't tried to compile this, but it is probably close enough to get you started)...

    class MyText extends Ui.Text
    {
    hidden var _M_text;

    function initialize(params) {
    Text.initialize(params);

    var text = params[:text];
    if (text == null) {
    text = "";
    }
    setText(text);
    }

    function setText(text) {
    _M_text = text;
    Text.setText(_M_text);
    }

    function getText() {
    return _M_text;
    }
    }


    To use it with a layout, you'd have to replace the label entry in the xml with something like this...

    <!-- this is the old one... -->
    <!-- <label x="100" y="100" justification="Gfx.TEXT_JUSTIFY_CENTER | Gfx.TEXT_JUSTIFY_VCENTER" text="Zebra /> -->

    <!-- this is the replacement -->
    <class id="theLabel" class="MyText">
    <param name="locX">100</param>
    <param name="locY">100</param>
    <param name="justification">Gfx.TEXT_JUSTIFY_CENTER | Gfx.TEXT_JUSTIFY_VCENTER</param>
    <param name="text">Zebra</param>
    </class>