Button's text gets wrong alignment after a setText() call on a TextView

前端 未结 1 545
再見小時候
再見小時候 2021-01-28 05:46

In my case I have an activity with a TableLayout which contains a few views such as a Button with id \'Number1\' and a TextView

相关标签:
1条回答
  • 2021-01-28 06:11

    After looking at the few similar occurrences on Stack Overflow like this, I tried a few different things including programmatically setting the text of the Button and also setting its gravity and padding again. None of this worked.

    I arrived at this solution by trial and error - Hide and then show the button before and after the offending call to setText. Also, note that you have to set visibility to GONE rather than INVISIBLE. This is possibly forcing the layout engine to create the button again, with the correct alignment.

    New event handler shown below.

    public void buttonNumberClick(View view) {
    
        TextView passwordText = (TextView) findViewById(R.id.password);
    
        Button sourceButton = (Button)view;
    
        String sourceText = sourceButton.getText().toString();
        String text = passwordText.getText().toString();
        if (text.length() < 4) {
            int number = Integer.parseInt(sourceText);
            String newText = text + Integer.toString(number);
    
            // Fix the issue of the button text being mis-aligned after the below call to setText.
            sourceButton.setVisibility(View.GONE);
    
            passwordText.setText(newText);
    
            // Fix the issue of the button text being mis-aligned after the above call to setText.
            sourceButton.setVisibility(View.VISIBLE);
        }
    }
    
    0 讨论(0)
提交回复
热议问题