Android列表展示和手指滑動分頁
如圖所示效果,列表+手勢分頁
java程式碼:
- privatefinalstaticStringTAG=AlarmCenterActivity.class.getName();
- privateScrollLayoutmScrollLayout;
- privateList<SpinnerItem>agentList=newArrayList<SpinnerItem>();
- privateSpinnersp_agent;//主機下拉框
- privateEditTextealarm_name;//例項名稱
- privateButtonserach_btn;//搜尋按鈕
- privateScrollPageControlViewpageControl;
- publicMyHandlermyHandler;
- privateDataLoadingdataLoad;
- List<Map>list=newArrayList<Map>();//web端獲取的資料
- //存放下拉選中的值
- StringtmpAgent="";//主機
- //告警中心列表
- finalStringALARM_URL="xxxxxx";
- //主機下拉
- finalStringAGENT_URL="xxxxxxxxxx";
- //查詢條件--主機名稱
- Strings_agent_name="";
- //查詢條件--例項名稱
- Strings_alarm_name=""
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_alarmcenter);
- initUI();
- Toast.makeText(AlarmCenterActivity.this,"正在載入資料...",Toast.LENGTH_SHORT).show();
- //起一個執行緒更新資料
- MyThreadm=newMyThread();
- newThread(m).start();
- }
- // 獲取元件初始化值
- privatevoidinitUI(){
- dataLoad=newDataLoading();
- mScrollLayout=(ScrollLayout)findViewById(R.id.ScrollLayoutTest);
- myHandler=newMyHandler(this,1);
- sp_agent=(Spinner)findViewById(R.id.sp_agent);
- ealarm_name=(EditText)findViewById(R.id.Ealarm_name);
- serach_btn=(Button)findViewById(R.id.search);
- //主機下拉資料來源
- List<NameValuePair>params=newArrayList<NameValuePair>();
- params.add(newBasicNameValuePair("id","agent_id"));
- params.add(newBasicNameValuePair("name","agent_name"));
- try{
- StringstrAgents=HttpIface.doPost(AGENT_URL,params);
- JSONObjectjson=newJSONObject(strAgents);
- Iterator<String>it=json.keys();
- SpinnerItemspinnerItem;
- Stringkey;
- //預設全部
- SpinnerItemadd_spinnerItem=newSpinnerItem("","全部");
- agentList.add(add_spinnerItem);
- while(it.hasNext()){
- key=it.next();
- spinnerItem=newSpinnerItem(key,(String)json.get(key));
- agentList.add(spinnerItem);
- }
- }catch(JSONExceptione){
- Log.e(TAG,"jsonconverterror!");
- e.printStackTrace();
- }catch(ClientProtocolExceptione){
- Log.e(TAG,"HttpIface.doPostClientProtocolException");
- e.printStackTrace();
- }catch(IOExceptione){
- Stringmessage="";
- if(message.indexOf("Theoperationtimedout")>-1){
- message="呼叫服務超時!";
- }else{
- message="呼叫服務出現網路異常!";
- }
- DialogUtil.displayError(AlarmCenterActivity.this,message,newOnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- }
- });
- Log.e(TAG,"呼叫服務超時或出現網路異常:"+ExceptionHandler.getErrorMessage(e));
- }
- /**
- *下拉框處理
- */
- //將可選內容與ArrayAdapter連線
- ArrayAdapters_agent_adapter=newArrayAdapter(this,android.R.layout.simple_spinner_item,agentList);
- //設定下拉列表的風格
- s_agent_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- //將s_agent_adapter新增到sp_agent中
- sp_agent.setAdapter(s_agent_adapter);
- //新增主機下拉框Spinner事件監聽
- sp_agent.setOnItemSelectedListener(newSpinner.OnItemSelectedListener(){
- @Override
- publicvoidonItemSelected(AdapterView<?>arg0,Viewarg1,
- intarg2,longarg3){
- tmpAgent=agentList.get(arg2).getKey();
- //設定顯示當前選擇的項
- arg0.setVisibility(View.VISIBLE);
- }
- @Override
- publicvoidonNothingSelected(AdapterView<?>arg0){
- arg0.setVisibility(View.VISIBLE);
- }
- });
- //查詢按鈕的事件監聽
- serach_btn.setOnClickListener(newButton.OnClickListener(){
- publicvoidonClick(Viewv){
- s_alarm_name=ealarm_name.getText().toString();
- s_agent_name=tmpAgent;
- mScrollLayout.removeAllViews();
- //重新載入
- list.clear();
- getListData();
- inttotalPages=0;
- if((list.size()%AlarmCenterAdapter.APP_PAGE_SIZE)==0){
- totalPages=list.size()/AlarmCenterAdapter.APP_PAGE_SIZE;
- }else{
- totalPages=list.size()/AlarmCenterAdapter.APP_PAGE_SIZE+1;
- }
- for(inti=0;i<totalPages;i++){
- ListViewappPage=newListView(AlarmCenterActivity.this);
- appPage.setAdapter(newAlarmCenterAdapter(AlarmCenterActivity.this,list,i));
- appPage.setOnItemClickListener(listener);
- mScrollLayout.addView(appPage);
- }
- //載入分頁
- pageControl=(ScrollPageControlView)findViewById(R.id.pageControl);
- pageControl.bindScrollViewGroup(mScrollLayout);
- //載入分頁資料
- dataLoad.bindScrollViewGroup(mScrollLayout);
- mScrollLayout.snapToScreen(0);
- }
- });
- }
- //更新後臺資料
- classMyThreadimplementsRunnable{
- publicvoidrun(){
- Messagemsg=myHandler.obtainMessage();
- Bundlebundle=newBundle();//存放資料
- getListData();
- JSONArrayja=newJSONArray(list);
- bundle.putString("alarmList",ja.toString());
- msg.setData(bundle);
- AlarmCenterActivity.this.myHandler.sendMessage(msg);//向Handler傳送訊息,更新UI
- }
- }
- //獲取資料
- classMyHandlerextendsHandler{
- privateAlarmCenterActivitymContext;
- publicMyHandler(Contextconn,inta){
- mContext=(AlarmCenterActivity)conn;
- }
- //子類必須重寫此方法,接收資料
- @Override
- publicvoidhandleMessage(Messagemsg){
- super.handleMessage(msg);
- Bundlebundle=msg.getData();
- StringalarmList=bundle.getString("alarmList");
- if(null!=alarmList){
- inttotalPages=0;
- if((list.size()%AlarmCenterAdapter.APP_PAGE_SIZE)==0){
- totalPages=list.size()/AlarmCenterAdapter.APP_PAGE_SIZE;
- }else{
- totalPages=list.size()/AlarmCenterAdapter.APP_PAGE_SIZE+1;
- }
- for(inti=0;i<totalPages;i++){
- ListViewappPage=newListView(mContext);
- appPage.setAdapter(newAlarmCenterAdapter(mContext,list,i));
- appPage.setOnItemClickListener(listener);
- mScrollLayout.addView(appPage);
- }
- //載入分頁
- pageControl=(ScrollPageControlView)findViewById(R.id.pageControl);
- pageControl.bindScrollViewGroup(mScrollLayout);
- //載入分頁資料
- dataLoad.bindScrollViewGroup(mScrollLayout);
- }
- }
- }
- //從伺服器獲取資料並轉換
- publicvoidgetListData(){
- Map<String,String>map=null;
- StringstrResult=HttpIface.doGet(ALARM_URL);
- if(!"".equals(strResult)&&null!=strResult){
- JSONTokenerjsonParser=newJSONTokener(strResult);
- JSONObjectjsonObject;
- try{
- jsonObject=(JSONObject)jsonParser.nextValue();
- Stringprgjson=jsonObject.getString("alarmCur");
- JSONArrayjsonArray=newJSONArray(prgjson);
- for(inti=0;i<jsonArray.length();i++){//
- JSONObjectitem=jsonArray.getJSONObject(i);//每條記錄又由幾個Object物件組成
- Stringkpi_instance_id=item.getString("KPI_INSTANCE_ID");//獲取物件對應的值
- Stringagent_name=item.getString("AGENT_NAME");//主機
- 。。。。。。
- //查詢條件全部不為空
- if(!s_agent_name.equals("")&&!s_alarm_name.equals("")){
- if(agent_name.equals(s_agent_name)&&kpi_instance_name.trim().indexOf(s_alarm_name)!=-1){
- map=newHashMap<String,String>();//存放到MAP裡面
- map.put("kpi_instance_id",kpi_instance_id);
- map.put("agent_name",agent_name);
- 。。。。。。
- list.add(map);
- }
- }
- //按程式名稱查詢
- if(s_agent_name.equals("")&&!s_alarm_name.equals("")){
- if(kpi_instance_name.trim().indexOf(s_alarm_name)!=-1){
- map=newHashMap<String,String>();//存放到MAP裡面
- map.put("kpi_instance_id",kpi_instance_id);
- map.put("agent_name",agent_name);
- 。。。。。。
- list.add(map);
- }
- }
- //按主機名稱模糊查詢
- if(!s_agent_name.equals("")&&s_alarm_name.equals("")){
- if(agent_name.equals(s_agent_name)){
- map=newHashMap<String,String>();//存放到MAP裡面
- map.put("kpi_instance_id",kpi_instance_id);
- map.put("agent_name",agent_name);
- 。。。。。。
- list.add(map);
- }
- }
- //查詢全部
- if(s_agent_name.equals("")&&s_alarm_name.equals("")){
- map=newHashMap<String,String>();//存放到MAP裡面
- map.put("kpi_instance_id",kpi_instance_id);
- map.put("agent_name",agent_name);
- 。。。。。。。
- map.put("user_id_c",user_id_c);
- list.add(map);
- }
- }
- }catch(JSONExceptione){
- e.printStackTrace();
- }
- }
- }
- //分頁資料
- classDataLoading{
- privateintcount;
- publicvoidbindScrollViewGroup(ScrollLayoutscrollViewGroup){
- this.count=scrollViewGroup.getChildCount();
- scrollViewGroup.setOnScreenChangeListenerDataLoad(newOnScreenChangeListenerDataLoad(){
- publicvoidonScreenChange(intcurrentIndex){
- Log.i(TAG,"onScreenChange頁碼="+currentIndex);
- generatePageControl(currentIndex);
- }
- });
- }
- privatevoidgeneratePageControl(intcurrentIndex){
- if(count==currentIndex+1){
- }
- }
- }
//列表展示給各列賦值
- //獲取元件賦值
- publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
- //TODOAuto-generatedmethodstub
- MapappInfo=mList.get(position);
- AppItemappItem;
- if(convertView==null){
- Viewv=LayoutInflater.from(mContext).inflate(R.layout.item_alarmcenter,null);
- appItem=newAppItem();
- appItem.num=(TextView)v.findViewById(R.id.num);
- appItem.agent_name=(TextView)v.findViewById(R.id.agent_name);
- 。。。。。。。。
- v.setTag(appItem);
- convertView=v;
- }else{
- appItem=(AppItem)convertView.getTag();
- }
- //賦值
- appItem.num.setText(position+1+"");
- appItem.agent_name.setText(appInfo.get("agent_name")==null?"":appInfo.get("agent_name").toString());
- appItem.coll_value.setText(appInfo.get("coll_value")==null?"":appInfo.get("coll_value").toString());
- appItem.kpi_instance_name.setText(appInfo.get("kpi_instance_name")==null?"":appInfo.get("kpi_instance_name").toString());
- 。。。。。。
- returnconvertView;
- }
查詢元件和列表表頭的XML list_alarmcenter.xml
- <!--查詢條件-->
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
- <LinearLayout
- android:layout_width="0dip"
- android:layout_height="wrap_content"
- android:layout_weight="9"
- android:background="@drawable/sys_btn_query_pressed"
- android:gravity="center_vertical|left"
- android:orientation="horizontal">
- <TextView
- android:id="@+id/txtagent"
- style="@style/label_text"
- android:layout_width="0dip"
- android:layout_weight="1"
- android:text="主機:"/>
- <Spinner
- android:id="@+id/sp_agent"
- style="@style/edit_text"
- android:layout_width="0dip"
- android:layout_height="wrap_content"
- android:layout_weight="2"
- android:gravity="left"/>
- </LinearLayout>
- <Button
- android:id="@+id/search"
- style="@style/button"
- android:layout_width="0dip"
- android:layout_marginLeft="20dip"
- android:layout_weight="1"/>
- </LinearLayout>
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="5dip"
- android:orientation="vertical">
- <!--標題-->
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="@drawable/page_title_bg">
- <Viewstyle="@style/vertical_layout"/>
- <TextView
- android:id="@+id/alarm_num"
- android:layout_width="70dp"
- android:layout_height="wrap_content"
- android:gravity="center_vertical|center_horizontal"
- android:padding="10dp"
- android:singleLine="true"
- android:text="序號"
- android:textColor="#000000"
- android:textSize="16dp"
- android:textStyle="bold"/>
- <Viewstyle="@style/vertical_layout"/>
- <TextView
- android:id="@+id/textView1"
- android:layout_width="160dp"
- android:layout_height="wrap_content"
- android:gravity="center_vertical|center_horizontal"
- android:padding="10dp"
- android:singleLine="true"
- android:text="主機"
- android:textColor="#000000"
- android:textSize="16dp"
- android:textStyle="bold"/>
- <Viewstyle="@style/vertical_layout"/>
- 。。。。。。。。
- </LinearLayout>
// 給列表賦值元件 item_alarmcenter.xml
- <LinearLayout
- android:id="@+id/view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="horizontal">
- <Viewstyle="@style/vertical_layout"/>
- <!--序號-->
- <TextView
- android:id="@+id/num"
- android:layout_width="70dp"
- android:layout_height="wrap_content"
- android:gravity="center_vertical|center_horizontal"
- android:padding="10dp"
- android:singleLine="true"
- android:textColor="#000000"
- android:textSize="16dp"/>
- <Viewstyle="@style/vertical_layout"/>
- <!--主機-->
- <TextView
- android:id="@+id/agent_name"
- android:layout_width="160dp"
- android:layout_height="wrap_content"
- android:gravity="center_vertical|center_horizontal"
- android:padding="10dp"
- android:singleLine="true"
- android:textColor="#000000"
- android:textSize="16dp"/>
- <Viewstyle="@style/vertical_layout"/>
- 。。。。。。。。
- </LinearLayout>
//滑動元件ScrollLayout scroll_page_main.xml
- <RelativeLayout
- android:id="@+id/myView"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <com.sunrise.common.component.ScrollLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/ScrollLayoutTest"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"/>
- <com.sunrise.common.component.ScrollPageControlView
- android:id="@+id/pageControl"
- android:layout_width="fill_parent"
- android:layout_height="40px"
- android:layout_alignParentBottom="true"
- android:gravity="center"/>
- </RelativeLayout>
以上倆個xml 檔案 分別引入到總的 xml 檔案中。
- <includelayout="@layout/list_alarmcenter"/>
- <includelayout="@layout/scroll_page_main"/>
列表展示詳解:
listView開始繪製的時候,首先呼叫getCount()函式,根據他的返回值得到listView的長度,然後根據這個長度,呼叫getView()逐一繪製每一行。如果你的getCount()返回值是0的話,列表將不顯示同樣return 1,就只顯示一行。
getView()有三個引數,position表示將顯示的是第幾行,covertView是從佈局檔案中inflate來的佈局。我們用LayoutInflater的方法將定義好的 item_alarmcenter.xml檔案提取成View例項用來顯示。然後將xml檔案中的各個元件例項化(簡單的findViewById()方法)。這樣便可以將資料對應到各個元件上了。至此一個自定義的listView就完成了,現在讓我們回過頭從新審視這個過程。系統要繪製ListView了,他首先獲得要繪製的這個列表的長度,然後開始繪製第一行,怎麼繪製呢?呼叫getView()函式。在這個函式裡面首先獲得一個View(實際上是一個ViewGroup),然後再例項並設定各個元件,顯示之。好了,繪製完這一行了。那 再繪製下一行,直到繪完為止。
手勢滑動:
1. 該類和LinearLayout、RelativeLayout等佈局都是ViewGroup的子類。LinearLayout可以在屬性中指定view的排列方式——橫向或縱向,而我們自己寫的這個類是通過onLayout(boolean changed, int l, int t, int r, int b)方法來自行指定排列方向的。我們這裡指定的是橫向。
2. 該類中用到了一些我們不常用的類,如VelocityTracker和Scroller,大家可以參考Android開發文件研究一下。
轉載於:https://blog.51cto.com/hanyijun85/1175627