如何保存ListView的滚动位置

时间:2017-01-10 00:56:08

标签: android listview

我设计了一个有2个活动的应用程序,第一个(all_activity)包含使用BaseAdapter的列表视图。当用户点击其中一个项目时,它将开始一个新活动(Story_Detalies)包含列表视图中项目的信息。

我为(Story_Detalies)活动创建(all_activity)父级,并在(Story_Detalies)活动中使用此代码

<?php
session_start();
?>

<h1 id="message" class="contentHeader">Welcome<br>Please log in</h1>
    <br>
    <form id="form" method="post" style="height:250px;" ">
      <h1 id="contentSignup" class="contentSignup">Log in</h1>
      <input type="text" name="username" pattern="[A-Za-z0-9]{4,30}" title="4 to 30 alphanumeric characters" placeholder="Username" required="required" />
      <br>
      <input type="password" name="password" pattern="[A-Za-z0-9]{6,25}" title="6 to 25 alphanumeric characters" placeholder="Password"  required="required" />
      <br>
      <button type="submit" class="Submit" name="submits">Submit</button>
      <?php
        if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['submits']))
        {

                $user = trim($_POST['username']);
                $pass = trim($_POST['password']);

                $file = "/private/data.csv";
                $handle = fopen($file, "r") or die('ERROR OPEN FILE!');

          while (($data = fgetcsv($handle)) !== FALSE) {
            if ($data[0] == $username && $data[1] == hash('sha256', $password) ){
                $_SESSION['user'] = $username;
                header("Location: ./home.php");
                $success = true;
                break;
            }
          }


                if (!$success)
                {
            echo '<script type="text/javascript">document.getElementById("message").style.color="red";</script>';
            echo '<script type="text/javascript">document.getElementById("message").innerHTML="Wrong username or password";</script>';
                }

                fclose($handle);
        }
      ?>
    </form>

它会显示一个箭头以转到上一个活动。

listview有很多项目,所以当用户点击箭头时,我希望listview能够滚动到之前的那个点。

这是我在oncreate()中的listview代码: -

 getSupportActionBar().setDisplayHomeAsUpEnabled(true);

1 个答案:

答案 0 :(得分:0)

您可以使用getFirstVisiblePosition()找出屏幕上第一个项目。接下来,您可以迭代子项,直到找到与第一个可见位置对应的子项,然后使用getTop()计算出它的垂直偏移量。

int position = listView.getFirstVisiblePosition();
int offset = 0;
for (int i = 0; i < listView.getChildCount(); i++) {
    View child = listView.getChildAt(i);
    if (listView.getPositionForView(child) == position) {
        offset = child.getTop();
        break;
    }
}

您可以保存这些值并在返回途中使用它们来拨打setSelectionFromTop(position offset)

相关问题