【问题标题】:Getting getLineCount() to work when screen is rotated旋转屏幕时让 getLineCount() 工作
【发布时间】:2022-02-01 09:58:52
【问题描述】:

我的记事本应用程序中有一个用户行计数器。但是,当应用程序处于横向与纵向时,EditText 中的文本量占用的空间更少,因此行数更少;所以行数必须在旋转时更新。

这是我为解决这个问题所做的:

我将以下方法添加到我的课程中,并将其添加到我的清单中的活动中:android:configChanges="orientation|screenSize"

我已经测试过了,它是在屏幕旋转时执行的方法。

@Override
public void onConfigurationChanged(Configuration newConfig) 
{
    super.onConfigurationChanged(newConfig);

    TextView linesDisplay = (TextView)findViewById(R.id.linesDisplay);
    EditText editText = (EditText)findViewById(R.id.editText);

    editText.setText("" + editText.getText().toString()); // this was just a test to see if the Edit Text needed to be "internally constructed"
    linesDisplay.setText("Lines: " + editText.getLineCount());

}

我写了 5 行纵向,它显示“Lines: 5”就好了。然后,当我旋转到横向时,它停留在“Lines: 5”(实际上是横向的 4 行)。再次旋转回纵向,现在转到“Lines: 4”。再次,回到横向,它转到“Lines: 5”。

似乎每次我旋转时,它都会显示方向之前的行数。也就是说,它会在旋转到横向时显示纵向 # 行,然后在旋转回纵向时显示横向 # 行,依此类推。

P --> “Lines: 5”(正确)
L --> "Lines: 5" (应该是 4)
P --> "Lines: 4" (应该是 5)
L --> "Lines: 5" (应该是 4)
...

^ 反之亦然,如果我从横向开始并继续向后旋转,它将落后(第一次旋转后),就像上面的情况一样。

有什么帮助吗?我认为这是因为它在 实际 旋转之前通过我的代码运行,所以行数落后于它应该是什么。 确定屏幕完全旋转后,有什么方法可以运行我的代码?

【问题讨论】:

    标签: android orientation


    【解决方案1】:

    把它放在你的onCreate 方法中:

    final View view = findViewById(R.id.idOfView);
    view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
    {
        @Override
        public void onGlobalLayout() 
        {
            TextView linesDisplay = (TextView)findViewById(R.id.linesDisplay);
            EditText editText = (EditText)findViewById(R.id.editText);
            linesDisplay.setText("Lines: " + editText.getLineCount());
        }
    });
    

    在你的XML:

    在您的父布局属性中,添加:android:id="@+id/idOfView"

    例如:

    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/idOfView"
        android:windowSoftInputMode="adjustResize"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
            <!-- widgets -->
        </RelativeLayout>
    </ScrollView>
    

    或者这个:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/idOfView"
        android:windowSoftInputMode="adjustResize"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <!-- widgets -->
    </LinearLayout>
    

    partial reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多