Android總結1

瓜瓜東西發表於2014-11-26

1 tabhost 方式

1.1

一概述

    提供Tab頁的視窗檢視容器,它有倆個children,一組是使用者可以選擇指定Tab頁的標籤,另一組是FrameLayout用來顯示該Tab頁的內容。個別元素通常控制使用這個容器物件,而不是設定在子元素本身的值。

二、重要方法

addTab(TabHost.TabSpec tabSpec):新增一項Tab

clearAllTabs():清除所有與之相關聯的Tab.

getCurrentTab():返回當前Tab.

getTabContentView():返回包含內容的FrameLayout

newTabSpec(String tag):返回一個與之關聯的新的TabSpec

三、例項

1.佈局檔案,需要使用FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
   android:layout_height="match_parent">

    <TextViewandroid:id="@+id/view1"
       android:background="@drawable/b"
       android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="1"/>

    <TextViewandroid:id="@+id/view2"
       android:background="@drawable/c"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
        android:text="2"/>

    <TextViewandroid:id="@+id/view3"
       android:background="@drawable/d"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
        android:text="3"/>

</FrameLayout>

 2.繼承TabActivity

public class TabHostDemo extends TabActivity

3.獲取次此abHost

 TabHost tabHost = getTabHost();

4.設定佈局

LayoutInflater.from(this).inflate(R.layout.tabhostpage,tabHost.getTabContentView(), true);

5.新增Tab

 tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1")
                .setContent(R.id.view1));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab2")
                .setContent(R.id.view2));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab3")
                .setContent(R.id.view3));

1.2 使得tab頁面顯示在下面

android:gravity=bottom

2 第二種方法

Java程式碼  

1. <?xml version="1.0" encoding="UTF-8"?>  

2. <selector  

3.   xmlns:android="http://schemas.android.com/apk/res/android">  

4.     <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_timeline_normal" /></span>  

5.     <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/tab_timeline_active" /></span>  

6.     <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_timeline_normal" /></span>  

7.     <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/tab_timeline_active" /></span>  

8.     <item android:state_pressed="true" android:drawable="@drawable/tab_timeline_normal" /></span>  

9. </selector>  


注意一定要繼承TabActivity 

Java程式碼  

1. public class MainActivity extends TabActivity {  

2.     private TabHost tabHost;  

3.     private RadioGroup mainbtGroup;  

4.     private static final String HOME = "主頁";  

5.     private static final String REFER = "提及";  

6.     private static final String SECRET = "私信";  

7.     private static final String SEARCH = "搜尋";  

8.     private static final String ATTENTIION = "關注";  

9.       

10.  

11.    @Override  

12.    public void onCreate(Bundle savedInstanceState) {  

13.        super.onCreate(savedInstanceState);  

14.        setContentView(R.layout.tabhost);//設定選項卡使用的佈局檔案  

15.          

16.        tabHost = this.getTabHost();  

17.  

18.        View view1 = View.inflate(MainActivity.this, R.layout.tab, null);  

19.        ((ImageView) view1.findViewById(R.id.tab_imageview_icon)).setImageResource(R.drawable.tab_timeline_selector);//設定每一個tab的圖示  

20.        ((TextView) view1.findViewById(R.id.tab_textview_title)).setText(HOME);  

21.  

22.        TabHost.TabSpec spec1 = tabHost.newTabSpec(HOME)  

23.                .setIndicator(view1)  

24.                .setContent(new Intent(this, HomeTimeLineActivity.class));  

25.        tabHost.addTab(spec1);  

26.          

27.        View view2 = View.inflate(MainActivity.this, R.layout.tab, null);  

28.        ((ImageView) view2.findViewById(R.id.tab_imageview_icon)).setImageResource(R.drawable.tab_atme_selector);  

29.        ((TextView) view2.findViewById(R.id.tab_textview_title)).setText(REFER);  

30.  

31.        TabHost.TabSpec spec2 = tabHost.newTabSpec(REFER)  

32.                .setIndicator(view2)  

33.                .setContent(new Intent(this, ReferActivity.class));  

34.        tabHost.addTab(spec2);  

35.          

36.        View view3 = View.inflate(MainActivity.this, R.layout.tab, null);  

37.        ((ImageView) view3.findViewById(R.id.tab_imageview_icon)).setImageResource(R.drawable.tab_message_selector);  

38.        ((TextView) view3.findViewById(R.id.tab_textview_title)).setText(SECRET);  

39.  

40.        TabHost.TabSpec spec3 = tabHost.newTabSpec(SECRET)  

41.                .setIndicator(view3)  

42.                .setContent(new Intent(this, MessageActivity.class));  

43.        tabHost.addTab(spec3);  

44.          

45.        View view4 = View.inflate(MainActivity.this, R.layout.tab, null);  

46.        ((ImageView) view4.findViewById(R.id.tab_imageview_icon)).setImageResource(R.drawable.tab_explore_selector);  

47.        ((TextView) view4.findViewById(R.id.tab_textview_title)).setText(SEARCH);  

48.  

49.        TabHost.TabSpec spec4 = tabHost.newTabSpec(SEARCH)  

50.                .setIndicator(view4)  

51.                .setContent(new Intent(this, SearchActivity.class));  

52.        tabHost.addTab(spec4);  

53.          

54.        View view5 = View.inflate(MainActivity.this, R.layout.tab, null);  

55.        ((ImageView) view5.findViewById(R.id.tab_imageview_icon)).setImageResource(R.drawable.tab_focus_selector);  

56.        ((TextView) view5.findViewById(R.id.tab_textview_title)).setText(ATTENTIION);  

57.  

58.        TabHost.TabSpec spec5 = tabHost.newTabSpec(ATTENTIION)  

59.                .setIndicator(view5)  

60.                .setContent(new Intent(this, AttentionActivity.class));  

61.        tabHost.addTab(spec5);  

62.    }  


下面的就是tabhost佈局檔案關鍵是tabhosttabcontenttabs這三個id一定要正確 

Java程式碼  

1. <?xml version="1.0" encoding="UTF-8"?>  

2. <TabHost android:id="@android:id/tabhost"  android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">  

3.     <RelativeLayout android:orientation="vertical"  

4.         android:layout_width="fill_parent" android:layout_height="fill_parent">  

5.         <FrameLayout android:id="@android:id/tabcontent"  

6.             android:layout_width="fill_parent" android:layout_height="fill_parent" />  

7.         <TabWidget android:id="@android:id/tabs" <span style="background-color: #ff0000;">android:background="@drawable/tab_bkg"</span> android:fadingEdge="none"  

8.             android:fadingEdgeLength="0.0px" android:layout_width="fill_parent"  

9.             android:layout_height="wrap_content"  

10.            android:layout_alignParentBottom="true" />  

11.    </RelativeLayout>  

12.</TabHost>  

 

Java程式碼  

1. android:layout_alignParentBottom="true" 把tab的五個按鈕挨著父控制元件的底部,在android裡面RelativeLayout很好用  


下面的是每一個tab項的佈局檔案上面是圖片下面是文字 

Java程式碼  

1. <?xml version="1.0" encoding="UTF-8"?>  

2. <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"  

3.   xmlns:android="http://schemas.android.com/apk/res/android">  

4.     <ImageView android:id="@+id/tab_imageview_icon" android:layout_width="fill_parent" android:layout_height="32.0dip" android:scaleType="fitCenter" />  

5.     <TextView android:id="@+id/tab_textview_title" android:textSize="11.0sp"  android:ellipsize="marquee" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" android:marqueeRepeatLimit="1" />  

6. </LinearLayout>  

 

2 列表顯示資料 listview

第一種是用SimpleAdapter建立(要求繫結的資料是List<HashMap<String, Object>>資料型別)

第二種是用SimpleCursorAdapter建立(要求繫結的資料是Cursor資料型別)

顯示效果如圖所示:

介面佈局:

item.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!--item -->  
  3. <LinearLayout  
  4.   xmlns:Android="http://schemas.android.com/apk/res/android"  
  5.   android:orientation="horizontal"  
  6.   android:layout_width="fill_parent"  
  7.   android:layout_height="fill_parent">  
  8.   <!-- 名稱 -->  
  9.   <TextView  
  10.    android:layout_width="130dp"  
  11.    android:layout_height="wrap_content"  
  12.    android:id="@+id/name"  
  13.   />  
  14.   <!-- 電話 -->  
  15.   <TextView  
  16.    android:layout_width="150dp"  
  17.    android:layout_height="wrap_content"  
  18.    android:id="@+id/phone"  
  19.   />  
  20.   <!-- 存款 -->  
  21.   <TextView  
  22.    android:layout_width="fill_parent"  
  23.    android:layout_height="wrap_content"  
  24.    android:id="@+id/amount"  
  25.   />  
  26. </LinearLayout>  

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.  <!-- 標題 -->  
  8.  <LinearLayout  
  9.   android:orientation="horizontal"  
  10.   android:layout_width="fill_parent"  
  11.   android:layout_height="wrap_content">  
  12.     
  13.   <TextView  
  14.    android:layout_width="130dp"  
  15.    android:layout_height="wrap_content"  
  16.    android:text="姓名"  
  17.   />  
  18.    
  19.    <TextView  
  20.    android:layout_width="150dp"  
  21.    android:layout_height="wrap_content"  
  22.    android:text="電話"  
  23.   />  
  24.     
  25.   <TextView  
  26.    android:layout_width="fill_parent"  
  27.    android:layout_height="wrap_content"  
  28.    android:text="存款"  
  29.   />  
  30.      
  31. </LinearLayout>  
  32.  <!-- ListView控制元件 -->  
  33. <ListView    
  34.     android:layout_width="fill_parent"   
  35.     android:layout_height="fill_parent"   
  36.     android:id="@+id/listView"  
  37.     />  
  38. </LinearLayout>  

使用SimpleAdapter進行資料繫結

  1. public class MainActivity extends Activity {  
  2.     private PersonService service;  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.main);  
  7.         service = new PersonService(this);  
  8.         ListView listView = (ListView) this.findViewById(R.id.listView);  
  9.           
  10.         //獲取到集合資料  
  11.         List<Person> persons = service.getScrollData(0, 10);  
  12.         List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();  
  13.         for(Person person : persons){  
  14.             HashMap<String, Object> item = new HashMap<String, Object>();  
  15.             item.put("id", person.getId());  
  16.             item.put("name", person.getName());  
  17.             item.put("phone", person.getPhone());  
  18.             item.put("amount", person.getAmount());  
  19.             data.add(item);  
  20.         }  
  21.        //建立SimpleAdapter介面卡將資料繫結到item顯示控制元件上  
  22.        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,   
  23.                 new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});  
  24.        //實現列表的顯示  
  25.        listView.setAdapter(adapter);  
  26.        //條目點選事件  
  27.        listView.setOnItemClickListener(new ItemClickListener());  
  28.     }  
  29.        //獲取點選事件      
  30.     private final class ItemClickListener implements OnItemClickListener{  
  31.   
  32.         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  33.             ListView listView = (ListView) parent;  
  34.             HashMap<String, Object> data = (HashMap<String, Object>) listView.getItemAtPosition(position);  
  35.             String personid = data.get("id").toString();  
  36.             Toast.makeText(getApplicationContext(), personid, 1).show();  
  37.         }  
  38.     }  
  39. }  

使用SimpleCursorAdapter進行資料繫結

  1. public class MainActivity extends Activity {  
  2.     private PersonService service;  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.main);  
  7.         service = new PersonService(this);  
  8.         ListView listView = (ListView) this.findViewById(R.id.listView);  
  9.         //獲取遊標  
  10.         Cursor cursor = service.getCursorScrollData(0, 10);  
  11.         //建立SimpleCursorAdapter介面卡將資料繫結到item顯示控制元件上  
  12.         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,   
  13.                 new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});  
  14.         listView.setAdapter(adapter);  
  15.         //條目點選事件  
  16.         listView.setOnItemClickListener(new ItemClickListener());  
  17.     }  
  18.       
  19.     private final class ItemClickListener implements OnItemClickListener{  
  20.   
  21.         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  22.             ListView listView = (ListView) parent;  
  23.             Cursor cursor = (Cursor) listView.getItemAtPosition(position);  
  24.             String personid = String.valueOf(cursor.getInt(cursor.getColumnIndex("_id")));  
  25.             Toast.makeText(getApplicationContext(), personid, 1).show();  
  26.         }  
  27.     }  
  28. }  

注意:使用第二種方式在獲取資料集合時必須指定主鍵"_id"

3 元件-list 長按事件

最近在學習android,對Android有些關鍵的知識點進行記錄,以便後面的學習。

在建立的Activity如果繼承自ListActivity類,則其預設擁有一個Listview控制元件提供使用, 下面主要就Listview中,item點選事件和長按事件的進行說明。

1、首先獲得listview例項;

[java] viewplaincopyprint?

1.  ListView lv = getListView();  

ListView lv = getListView();


2、新增點選事件

  對lv新增點選監聽器。

[java] viewplaincopyprint?

1.  lv.setOnItemClickListener(new OnItemClickListener() {  

2.              public void onItemClick(AdapterView<?> parent, View view,  

3.                      int position, long id) {  

4.                  // When clicked, show a toast with the TextView text  

5.                  TextView tv = (TextView)view.findViewById(R.id.textViewVideoTitle);  

6.                  Toast.makeText(getApplicationContext(),  

7.                          tv.getText(), Toast.LENGTH_SHORT).show();  

8.              }  

9.          });  

lv.setOnItemClickListener(new OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent, View view,
         int position, long id) {
       // When clicked, show a toast with the TextView text
       TextView tv = (TextView)view.findViewById(R.id.textViewVideoTitle);
       Toast.makeText(getApplicationContext(),
           tv.getText(), Toast.LENGTH_SHORT).show();
     }
    });

其中R.id.textViewVideoTitle 是Listview,item中的一個TextView控制元件。
3、新增長按事件

[java] viewplaincopyprint?

1.  lv.setOnItemLongClickListener(new OnItemLongClickListener(){  

2.              @Override  

3.              public boolean onItemLongClick(AdapterView<?> arg0, View arg1,  

4.                      int arg2, long arg3) {  

5.                  // TODO Auto-rated method stub   

6.                  // When clicked, show a toast with the TextView text  

7.                  TextView tv = (TextView)arg1.findViewById(R.id.textViewVideoTitle);  

8.                  Toast.makeText(getApplicationContext(),  

9.                          tv.getText(), Toast.LENGTH_SHORT).show();  

10.                 return false;  

11.             }  

12.         });  

lv.setOnItemLongClickListener(new OnItemLongClickListener(){
     @Override
     public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
        int arg2, long arg3) {
      // TODO Auto-generated method stub
      // When clicked, show a toast with the TextView text
      TextView tv = (TextView)arg1.findViewById(R.id.textViewVideoTitle);
      Toast.makeText(getApplicationContext(),
         tv.getText(), Toast.LENGTH_SHORT).show();
      return false;
     }
   });


備註:

對於缺少的包,在eclipse中按Ctrl+shift+O就可以自動引入。

4  長按彈出選單事件


/**

*知識點1:ListView item:兩種長按彈出選單方式
* 知識點2:ListView SimpleAdapter的使用
* 知識點 3:在java程式碼中建立一個ListView
*/

publicclass ListOnLongClickActivity extends Activity {
        private LinearLayoutmyListViewlayout;
        private ListView mListView;
        SimpleAdapter adapter;
        public int MID;

       // 建立一個List物件,用來存放列表項的每一行map資訊
        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();

       @Override
        public void onCreate(BundlesavedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.main);

               myListViewlayout = (LinearLayout) findViewById(R.id.myListViewlayout);
               mListView = new ListView(this);
               // 建立佈局引數
               LinearLayout.LayoutParams listviewParams = new LinearLayout.LayoutParams(
                               LinearLayout.LayoutParams.FILL_PARENT,
                               LinearLayout.LayoutParams.FILL_PARENT);
               // 當滑動列表上,預設顯示的黑色
               mListView.setCacheColorHint(Color.WHITE);
               // 將列表新增到流式佈局myListViewlayout中
               myListViewlayout.addView(mListView, listviewParams);

               FillListData();

               // 列表現的單機事件
               mListView.setOnItemClickListener(new OnItemClickListener() {

                       @Override
                       public void onItemClick(AdapterView<?> arg0, View arg1,
                                       int position, long id) {
                               /*
                                * 點選列表項時觸發onItemClick方法,四個引數含義分別為
                                * arg0:發生單擊事件的AdapterView
                                * arg1:AdapterView中被點選的View 
                                * position:當前點選的行在adapter的下標
                                * id:當前點選的行的id
                                */
                               Toast.makeText(ListOnLongClickActivity.this,
                                               "您選擇的是" +list.get(position).get("name").toString(),
                                               Toast.LENGTH_SHORT).show();
                       }
               });

               /**
                * Item 長按方式彈出選單多選方式1
                * Item 長按方式彈出選單多選方式2
                * ItemOnLongClick1()與ItemOnLongClick2()不共存,按實際需要選擇
                */
       //        ItemOnLongClick1();
               ItemOnLongClick2();
        }

       // 填充ListView資源
        private void FillListData() {

               adapter = new SimpleAdapter(ListOnLongClickActivity.this,
                               getListData(), R.layout.listviewrow, new String[] { "name",
                                               "price" }, new int[] { R.id.tv_name, R.id.tv_price });
               mListView.setAdapter(adapter);
        }

       private List<Map<String, Object>> getListData() {

               Map<String, Object> _map = new HashMap<String, Object>();
               _map.put("name", "小米");
               _map.put("price", "2350元");
               list.add(_map);

               _map = new HashMap<String, Object>();
               _map.put("name", "HTC G18");
               _map.put("price", "3340元");
               list.add(_map);

               _map = new HashMap<String, Object>();
               _map.put("name", "iphone 5");
               _map.put("price", "5450元");
               list.add(_map);

               _map = new HashMap<String, Object>();
               _map.put("name", "iPhone 4S");
               _map.put("price", "4650元");
               list.add(_map);

               _map = new HashMap<String, Object>();
               _map.put("name", "MOTO ME525");
               _map.put("price", "1345元");
               list.add(_map);
               return list;

       }

       private void ItemOnLongClick1() {
//注:setOnCreateContextMenuListener是與下面onContextItemSelected配套使用的
               mListView
                               .setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

                                       public void onCreateContextMenu(ContextMenu menu, View v,
                                                       ContextMenuInfo menuInfo) {
                                               menu.add(0, 0, 0, "購買");
                                               menu.add(0, 1, 0, "收藏");
                                               menu.add(0, 2, 0, "對比");

                                       }
                               });
        }

       // 長按選單響應函式
        public booleanonContextItemSelected(MenuItem item) {

               AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item
                               .getMenuInfo();
               MID = (int) info.id;// 這裡的info.id對應的就是資料庫中_id的值

               switch (item.getItemId()) {
               case 0:
                       // 新增操作
                       Toast.makeText(ListOnLongClickActivity.this,
                                       "新增",
                                       Toast.LENGTH_SHORT).show();
                       break;

               case 1:
                       // 刪除操作
                       break;

               case 2:
                       // 刪除ALL操作
                       break;

               default:
                       break;
               }

               return super.onContextItemSelected(item);

       }

       private void ItemOnLongClick2() {
               mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

                       @Override
                       public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       final int arg2, long arg3) {
                               list.remove(arg2);
                               new AlertDialog.Builder(ListOnLongClickActivity.this)
                                               .setTitle("對Item進行操作")
                                               .setItems(R.array.arrcontent,
                                                               new DialogInterface.OnClickListener() {
                                                                       public void onClick(DialogInterface dialog,
                                                                                       int which) {
                                                                               String[] PK = getResources()
                                                                                               .getStringArray(
                                                                                                               R.array.arrcontent);
                                                                               Toast.makeText(
                                                                                               ListOnLongClickActivity.this,
                                                                                               PK[which], Toast.LENGTH_LONG)
                                                                                               .show();
                                                                               if (PK[which].equals("刪除")) {
                                                                                       // 按照這種方式做刪除操作,這個if內的程式碼有bug,實際程式碼中按需操作
                                                                                       list.remove(arg2);
                                                                                       adapter = (SimpleAdapter) mListView
                                                                                                       .getAdapter();
                                                                                       if (!adapter.isEmpty()) {
                                                                                               adapter.notifyDataSetChanged(); // 實現資料的實時重新整理
                                                                                       }
                                                                               }
                                                                       }
                                                               })
                                               .setNegativeButton("取消",
                                                               new DialogInterface.OnClickListener() {
                                                                       public void onClick(DialogInterface dialog,
                                                                                       int which) {
                                                                               // TODO Auto-generated method stub

                                                                       }
                                                               }).show();
                               return true;
                       }
               });

       }
}

 


-----------
listviewrow.xml

程式碼片段, <?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:background="@drawable/listviewbg"
    android:orientation="vertical" >

   <TextView
        android:id="@+id/tv_name"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:textColor="@android:color/black" />

   <TextView
        android:id="@+id/tv_price"
       android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       android:textColor="@android:color/black" />

</LinearLayout>

 

 

相關文章