I am trying to align a CheckBoxField and TextField on LEFT and RIGHT respectively using an HorizontalFieldManager. But unfortunately the TextField is never visible.

I tried the same code with two buttons, and the buttons were visible without any trouble (one button on the right corner and the other on the left corner of the screen).

But I am not sure, why I can't acheive the same if I use a CheckBoxField. Here is my code,

checkBoxHorizontalFieldManager=new HorizontalFieldManager(HorizontalFieldManager.USE_ALL_WIDTH);
keepLoggedCheckboxField=new CheckboxField("keep Me Logged In", true,CheckboxField.FIELD_LEFT);

forgotPasswordTextField=new TextField(TextField.FIELD_RIGHT);
forgotPasswordTextField.setText("Forgot Password?");
checkBoxHorizontalFieldManager.add(keepLoggedCheckboxField);
checkBoxHorizontalFieldManager.add(forgotPasswordTextField);
add(checkBoxHorizontalFieldManager);

Screenshot

I even tried reducing the text length on both the fields. But still the same issue.

有帮助吗?

解决方案

I think there's two problems here.

Field Alignment

The problem is that a HorizontalFieldManager does not use the FIELD_RIGHT flag you're setting on the text field. HorizontalFieldManager just lays out fields left to right as you add them. See more here.

You can solve this problem a couple ways. See this question for two solutions.

TextField Width

I believe the TextField is also taking up all available width by default, and it lays out its text on the left side of the field, by default. So, only solving the field alignment problem won't be enough. You can fix this either of two ways: make the TextField draw its text right-aligned, or shrink the width of the TextField to just barely fit the text.

For the first solution, you can see a sample blog post I added here.

For the second solution, you can override Field#layout() in the TextField class. That solution, combined with one field alignment solution, might look like this:

checkBoxHorizontalFieldManager = new HorizontalFieldManager(HorizontalFieldManager.USE_ALL_WIDTH);
keepLoggedCheckboxField = new CheckboxField("keep Me Logged In", true, CheckboxField.FIELD_LEFT);
checkBoxHorizontalFieldManager.add(keepLoggedCheckboxField);

forgotPasswordTextField = new TextField(TextField.FIELD_RIGHT) {
    protected void layout(int w, int h) {
        super.layout(w, h);
        Font f = getFont();
        setExtent(getPaddingLeft() + f.getAdvance(getText()) + getPaddingRight(), 
                getPaddingTop() + f.getHeight() + getPaddingBottom());
    }
};
forgotPasswordTextField.setText("Forgot Password?");

VerticalFieldManager vfm = new VerticalFieldManager(Manager.USE_ALL_WIDTH);
vfm.add(forgotPasswordTextField);

checkBoxHorizontalFieldManager.add(vfm);
add(checkBoxHorizontalFieldManager);    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top