我正在为 Android 2.2+ 构建
我正在使用ListView
方法smoothScrollToPosition(0)
滚动回列表顶部。它在大多数情况下都有效,但是如果某些列表项的高度变得可变,那么smoothScrollToPosition(0)
当它到达更长的列表项时就会停止。
它是一个错误吗?还是我做错了什么?
Activity
这是产生问题的示例代码:
public class SimpleListViewActivity extends Activity {
private ListView mainListView ;
private Button btnScrollToTop ;
private ArrayAdapter<String> listAdapter ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainListView = (ListView) findViewById( R.id.mainListView );
// some test data
String[] planets = new String[] { "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40",
"Mercury","Venus", "Earth", "Mars",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n10",
"Jupiter", "Saturn","Uranus",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40",
"Neptune",
"Ceres",
"Pluto",
"Haumea",
"Makemake",
"Eris"
};
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
mainListView.setAdapter( listAdapter );
//scroll to top
btnScrollToTop = (Button) findViewById( R.id.btn_scroll_to_top);
btnScrollToTop.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mainListView.smoothScrollToPosition(0);
}
});
}
}
xml主布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/btn_scroll_to_top"
android:text="Scroll To Top"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
/>
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mainListView">
</ListView>
</LinearLayout>
列表行布局:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>