旋转屏幕时让getCountLine()工作

时间:2013-09-28 21:04:13

标签: android orientation

我的记事本应用中有一个用户线计数器。但是,当应用程序处于横向与纵向时,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”就好了。然后,当我旋转到横向时,它停留在“线条:5”(当它实际上是4条横向线)时。再次旋转回肖像,现在它转到“行:4”。再次回到横向,它变成了“Lines:5”。

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

P - > “行数:5”(正确)
L - > “行数:5”(应为4)
P - > “行数:4”(应为5)
L - > “行数:5”(应为4)
...

^它的工作方式相同,反之亦然,就像我从横向开始并继续向前旋转一样,它将落后于(在第一次旋转之后),就像上面的情况一样。

有任何帮助吗?我认为这是因为它在实际旋转之前运行了我的代码,因此行数落后于它应该是什么。在确定屏幕完全旋转后,有没有办法运行我的代码?

1 个答案:

答案 0 :(得分:2)

将其放入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