一个ListView的小Demo,根据点击的位置自动滑动到当前的位置。
主界面
`public class MainActivity extends Activity {
protected static final String TAG = “MainActivity”;
private List list = new ArrayList();
private ListView lv;
private int current_Position = 0;
private LayoutInflater inflater;
private adapter a;
private int firstVisiblePosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
inflater = LayoutInflater.from(this);
initData();
lv = (ListView) findViewById(R.id.listView1); firstVisiblePosition = lv.getFirstVisiblePosition(); a = new adapter(list); lv.setAdapter(a); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { current_Position = position; // int lastVisiblePosition = lv.getLastVisiblePosition(); int top = getScrollY(); lv.smoothScrollBy((view.getHeight())* (position - firstVisiblePosition) + top, 500); a.notifyDataSetChanged(); } }); } private void initData() { for (int i = 0; i < 20; i++) { list.add("Jack"+i); } } public int getScrollY() { View c = lv.getChildAt(0); if (c == null) { return 0; } firstVisiblePosition = lv.getFirstVisiblePosition(); int top = c.getTop(); return top; }
class adapter extends BaseAdapter{
private List<String> list; public adapter(List<String> list) { this.list=list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = inflater.inflate(R.layout.item, parent, false); View view = convertView.findViewById(R.id.view1); TextView tv = (TextView) convertView.findViewById(R.id.textView1); if(current_Position ==position){ view.setVisibility(View.VISIBLE); }else{ view.setVisibility(View.GONE); } tv.setText(list.get(position)); return convertView; }
}
}
主界面的XML就一个ListView
ListView的item
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <View android:id="@+id/view1" android:layout_width="5dp" android:background="#ff0000" android:layout_height="40dp" /> <TextView android:gravity="center_vertical" android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="40dp" android:text="TextView" /> </LinearLayout>
<p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>