2014-11-15 73 views
2

我想在Android中創建一個ListView。當我點擊一個項目時,我想讓它滾動到頂部。我怎樣才能做到這一點?下面是我想出來的活動類,項目選擇工作正常,但它不會在滾動到頂部Android的ListView如何滾動選定的項目頂部

public class MyListActivity extends ListActivity { 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile", 
     "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", 
     "Linux", "OS/2" }; 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, values); 
     setListAdapter(adapter); 
    } 

    @Override 
    protected void onListItemClick(ListView l, View v, int position, long id) { 
     String item = (String) getListAdapter().getItem(position); 
     //l.setSelection(2); 

     Toast.makeText(this, position + " selected", Toast.LENGTH_LONG).show(); 
     //l.smoothScrollToPosition(5); 

    } 
} 
+0

在這裏看到我的回答,http://stackoverflow.com/a/29345217/1881527 –

回答

1

嘗試使用此方法setSelection (int position)

設置當前選擇的項目。要支持覆蓋此方法的輔助功能子類,必須首先調用overridden超級方法。

1

根據這一https://stackoverflow.com/a/18133295/3225458,你應該嘗試post平滑滾動:

@Override 
protected void onListItemClick(final ListView l, View v, int position, long id) { 
    String item = (String) getListAdapter().getItem(position); 
    l.post(new Runnable() { 
     @Override 
     public void run() { 
      l.smoothScrollToPosition(pos); 
     } 
    }); 
    Toast.makeText(this, position + " selected", Toast.LENGTH_LONG).show(); 
} 
+0

我試了你的建議,但沒有滾動 – user1892775

11

使用此。將項目順利滾動到列表視圖的頂部。

int duration = 500; //miliseconds 
int offset = 0;  //fromListTop 

listview.smoothScrollToPositionFromTop(position,offset,duration); 
  • descrease時間,使滾動更快
+0

非常有用,謝謝! –

+0

謝謝@MohsenBahmanpoor。很簡單,我可以說和完美的工作 – Adam

+0

這應該是接受的答案 –

0

試試這個: -

yourListView.setOnItemClickListener(new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
        long arg3) { 
       int duration = 500; // miliseconds 
       int offset = 0; 
       yourListView.smoothScrollToPositionFromTop(arg2, offset, duration); 
       yourListView.setSelection(arg2); 
      } 
     });