Search code examples
androidandroid-edittextsettext

How do I use setText do set text of existing EditText item?


Edit: I'm an idiot, move on...

The code and xml is below. I'm not getting any errors, but the text doesn't display. Anyone know why this doesn't work?

Code:

public boolean onPrepareMenuOptions ( Menu menu ) {
    EditText currency = (EditText) menu.findItem ( R.id.currency );
    currency.setText ( "test" );
    return true;
}

@Override
public boolean onCreateOptionsMenu ( Menu menu ) {
    getMenuInflater ().inflate ( R.menu.new_project, menu );
    return true;
}

XML:

<EditText
    android:id="@+id/currency"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/currency_summary" />

Solution

  • I think the problem is that onPrepareMenuOptions is not being called. Here is what the documentation says:

    On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user opens the options menu (presses the Menu button).

    On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

    You could solve this problem in two ways:

    1) Method 1: Update the text at the time of onCreateMenuOptions (can update the XML file directly if you want)

    2) Method 2: Call invalidateOptionsMenu() somewhere in code, just before the menu is shown.

    Update: I noticed a bug in your code, should be calling super.onPrepareMenuOptions()

    public boolean onPrepareMenuOptions ( Menu menu ) {
        super.onPrepareOptionsMenu(menu); // this is important
        EditText currency = (EditText) menu.findItem ( R.id.currency );
        currency.setText ( "test" );
        return true;
    }
    
    @Override
    public boolean onCreateOptionsMenu ( Menu menu ) {
        getMenuInflater ().inflate ( R.menu.new_project, menu );
        return true;
    }    `