首页 > 代码库 > Android之Composite

Android之Composite

一、listView控件

1.使用listview对数据进行简单的绑定,这里使用Arrayadater适配器进行简单的数据绑定

技术分享

public class MainActivity extends Activity {    private ListView listView;    private ArrayAdapter<String> adapter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        listView=(ListView)this.findViewById(R.id.listView1);        adapter=new ArrayAdapter<String>(MainActivity.this,                 android.R.layout.simple_list_item_1, getDataSourece());        listView.setAdapter(adapter);    }    public List<String> getDataSourece() {        List<String> list=new ArrayList<String>();        for(int i =0;i<30;i++){                        list.add("bibly"+i);        }        return list;    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    }

2.自定义listview控件

技术分享使用SimpleAdapter+ListView

SimpleAdapter其中一个构造函数如下:

public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
    第一个参数:当前上下文对象。第二个参数:一个List类型的泛型集合,泛型类型必须继承之Map类型。第三个:布局资源的ID,

第四个参数:需要绑定的Key列表。第五个参数:与Key列表项对应的资源文件中的具体组件ID集合。

自定义一个布局文件image.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">      <ImageView         android:layout_width="wrap_content"         android:layout_height="wrap_content"        android:id="@+id/img">      </ImageView>        <TextView   android:id="@+id/txtName"   android:layout_width="wrap_content"   android:layout_height="wrap_content"  >  </TextView>    <TextView   android:paddingLeft="20sp"   android:id="@+id/txtLength"   android:layout_width="wrap_content"   android:layout_height="wrap_content"  >  </TextView>  </LinearLayout>

package com.example.mytestxml;import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.example.mytestxml.R.id;import com.example.mytestxml.R.string;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.ListView;import android.widget.SimpleAdapter;public class MainActivity extends Activity {    private ListView listView;    private ArrayAdapter<String> adapter;    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        listView=(ListView)this.findViewById(R.id.listView1);        button=(Button)this.findViewById(R.id.button1);        button.setOnClickListener(new View.OnClickListener() {                        @Override            public void onClick(View arg0) {                // TODO Auto-generated method stub                   String []from={"img","name","length"};                     int[]to={R.id.img,R.id.txtName,R.id.txtLength};                     SimpleAdapter adapter=new SimpleAdapter(MainActivity.this,getData(),                             R.layout.image, from, to);                     listView.setAdapter(adapter);              }        });        adapter=new ArrayAdapter<String>(MainActivity.this,                 android.R.layout.simple_list_item_1, getDataSourece());        listView.setAdapter(adapter);    }    public List<Map<String, Object>> getData() {        List<Map<String,Object>> lists=new ArrayList<Map<String,Object>>();        for(int i=0;i<4;i++){            Map<String,Object> map=new HashMap<String,Object>();            map.put("img", R.drawable.ic_launcher);            map.put("name", "SimpleAdapter"+i);            map.put("length", "300");            lists.add(map);        }        return lists;    }    public List<String> getDataSourece() {        List<String> list=new ArrayList<String>();        for(int i =0;i<30;i++){                        list.add("bibly"+i);        }        return list;    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    }

3.使用SimpleAdapter

activity_main.xml下更改代码

 

<?xml version="1.0" encoding="utf-8"?>    <LinearLayout       xmlns:android="http://schemas.android.com/apk/res/android"      android:orientation="horizontal"       android:layout_width="match_parent"      android:layout_height="match_parent">         <ImageView android:id="@+id/picture"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_margin="5dip"/>        <LinearLayout android:orientation="vertical"          android:layout_width="wrap_content"          android:layout_height="wrap_content">            <TextView android:id="@+id/title"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:textColor="#16CCDD"              android:textSize="22sp" />            <TextView android:id="@+id/info"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:textColor="#666666"              android:textSize="16sp" />      </LinearLayout>     </LinearLayout>

更改MainActivity.java

public class MainActivity extends ListActivity  {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        SimpleAdapter adapter = new SimpleAdapter(this,getData(),                  R.layout.activity_main,                  new String[]{"title","info","picture"},                  new int[]{R.id.title,R.id.info,R.id.picture});         setListAdapter(adapter);    }    private List<Map<String, Object>> getData() {          List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();          Map<String, Object> map = new HashMap<String, Object>();          map.put("title", "图片");          map.put("info", "美辰良景,给你无限的遐思,让人感觉无限温馨……");          map.put("picture", R.drawable.ic_launcher);          list.add(map);            map = new HashMap<String, Object>();          map.put("title", "音乐");          map.put("info", "轻曼音乐,令人如入仙境,如痴如醉……");          map.put("picture", R.drawable.ic_launcher);          list.add(map);            map = new HashMap<String, Object>();          map.put("title", "视频");          map.put("info", "震撼场景,360度的视觉捕获,一览无遗……");          map.put("picture", R.drawable.ic_launcher);          list.add(map);          return list;      }   }

注意这里的MainActivity extends ListActivity ,ListActivity和普通的Activity没有太大的差别,不同就是对显示ListView做了许多优化,方面显示而已。

4.使用SimpleAdapter+ListView读取xml数据并访问(使用dom解析的方式读取xml数据)

定义的xml数据

<?xml version="1.0" encoding="utf-8"?><channel><item id="0" url="http://www.baidu.com">百度</item><item id="1" url="http://www.qq.com">腾讯</item><item id="2" url="http://www.sina.com.cn">新浪</item><item id="3" url="http://www.taobao.com">淘宝</item></channel>

定义对应的类来读取数据

public class channel {        private String id;    private String url;    private String name;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

定义读取xml读取数据的类(使用Dom方式)

ublic class DomParserHelper {        public static List<channel> getChannelList(InputStream stream)    {        List<channel> list=new ArrayList<channel>();                //得到 DocumentBuilderFactory 对象, 由该对象可以得到 DocumentBuilder 对象        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();                try {            //得到DocumentBuilder对象            DocumentBuilder builder=factory.newDocumentBuilder();            //得到代表整个xml的Document对象            Document document=builder.parse(stream);            //得到 "根节点"             Element root=document.getDocumentElement();            //获取根节点的所有items的节点            NodeList items=root.getElementsByTagName("item");              //遍历所有节点            for(int i=0;i<items.getLength();i++)            {                channel chann=new channel();                Element item=(Element)items.item(i);                chann.setId(item.getAttribute("id"));                chann.setUrl(item.getAttribute("url"));                chann.setName(item.getFirstChild().getNodeValue());                list.add(chann);            }                    } catch (ParserConfigurationException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (SAXException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }                return list;    }}

private List<Map<String, String>> getData2() {        List<Map<String, String>> list = new ArrayList<Map<String, String>>();        InputStream stream = getResources().openRawResource(R.raw.channels);        List<channel> channlist = DomParserHelper.getChannelList(stream);        for (int i = 0; i < channlist.size(); i++) {            Map<String, String> map = new HashMap<String, String>();            channel chann = (channel) channlist.get(i);            map.put("id", chann.getId());            map.put("url", chann.getUrl());            map.put("name", chann.getName());            list.add(map);        }        return list;    }

button2.setOnClickListener(new View.OnClickListener() {                        @Override            public void onClick(View arg0) {                // TODO Auto-generated method stub                 String []from={"id","name","url"};                 int[]to={R.id.id,R.id.name,R.id.url};                SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,getData2(),                         R.layout.myxml, from, to);                  listView.setAdapter(adapter);              }        });

二、GridView控件

activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>      <GridView       xmlns:android="http://schemas.android.com/apk/res/android"         android:id="@+id/gridview"        android:layout_width="match_parent"         android:layout_height="match_parent"        android:numColumns="auto_fit"        android:verticalSpacing="10dp"        android:horizontalSpacing="10dp"        android:columnWidth="90dp"        android:stretchMode="columnWidth"        android:gravity="center"    />

添加grid.xml文件

<?xml version="1.0" encoding="utf-8"?>      <RelativeLayout              xmlns:android="http://schemas.android.com/apk/res/android"              android:layout_height="wrap_content"              android:paddingBottom="4dip" android:layout_width="fill_parent">             <ImageView                    android:layout_height="wrap_content"                    android:id="@+id/ItemImage"                    android:layout_width="wrap_content"                    android:layout_centerHorizontal="true">              </ImageView>             <TextView                    android:layout_width="wrap_content"                    android:layout_below="@+id/ItemImage"                    android:layout_height="wrap_content"                    android:text="TextView01"                    android:layout_centerHorizontal="true"                    android:id="@+id/ItemText">             </TextView>    </RelativeLayout>
public class MainActivity extends Activity {        @Override      public void onCreate(Bundle savedInstanceState) {             super.onCreate(savedInstanceState);             setContentView(R.layout.activity_main);             GridView gridview = (GridView) findViewById(R.id.gridview);                           //生成动态数组,并且转入数据              ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();             for(int i=0;i<10;i++){                HashMap<String, Object> map = new HashMap<String, Object>();                map.put("ItemImage", R.drawable.ic_launcher);//添加图像资源的ID                 map.put("ItemText", "NO."+String.valueOf(i));//按序号做ItemText                 lstImageItem.add(map);              }              //生成适配器的ImageItem <====> 动态数组的元素,两者一一对应               SimpleAdapter saImageItems = new SimpleAdapter(this,                                                       lstImageItem,//数据来源                                                          R.layout.grid,//grid的XML实现                                                                                                                 //动态数组与ImageItem对应的子项                                                                 new String[] {"ItemImage","ItemText"},                                                                                                                 //ImageItem的XML文件里面的一个ImageView,两个TextView ID                                                         new int[] {R.id.ItemImage,R.id.ItemText});              //添加并且显示               gridview.setAdapter(saImageItems);              //添加消息处理               gridview.setOnItemClickListener(new ItemClickListener());          }                    //当AdapterView被单击(触摸屏或者键盘),则返回的Item单击事件           class  ItemClickListener implements OnItemClickListener{              public void onItemClick(AdapterView<?> arg0,View arg1,int arg2,long arg3){                    HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);                    //显示所选Item的ItemText                     setTitle((String)item.get("ItemText"));              }                   }      }

三、SlidingDrawer

SlidingDrawer(滑动式抽屉)隐藏屏外的内容,并允许用户拖拽一个handle以显示隐藏的内容。SlidingDrawer可以在垂直或者水平使用。它由两个子视图组成:一个是用户拖拽的handle(柄),另一个是随着拖动变化的content(内容)。SlidingDrawer应当作为内部布局的覆盖来使用,也就是说SlidingDrawer内部应该使用FrameLayout或RelativeLayout布局。SlidingDrawer的大小决定了其内容显示时所占空间的大小,所以它的尺寸一般定义为match_parent。在XML布局中SlidingDrawer必须指定handle和content的id:

activity_main.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:orientation="vertical" >      <SlidingDrawer           android:id="@+id/slidingdraw"          android:layout_width="match_parent"          android:layout_height="match_parent"          android:handle="@+id/handle"          android:content="@+id/content"          >          <ListView               android:id="@id/content"              android:layout_width="match_parent"              android:layout_height="match_parent"              />                 <ImageView android:id="@id/handle"              android:src="@drawable/ic_launcher"              android:layout_width="88dip"              android:layout_height="44dip"               android:contentDescription="TODO"/>      </SlidingDrawer>    </LinearLayout>

MainActivity.java”文件

public class MainActivity extends Activity {    private SlidingDrawer mDrawer;    private ImageView mImageView;    private ListView lvNews;    private String a[] = { "互联网产品中的情感化设计", "有效导向社交产品的商业价值", "移动开发者:得90后者得天下",                 "用户体验:从App的加载页面说开去", "用扁平化的界面设计吸引用户", "实体与数字世界的交集",                 "网络社区用户成长的5个思考模式", "十大值得关注的传统企业电商", "2013年十大热点技术发展趋势","了解产品的开发环节:环形设计论",              "客户忠诚度的四个层次","在手机背面贴张‘纸‘就能轻松充电","互联网公司是怎样激发你的消费欲望的","高效工作的信息搜集及管理术" };     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mDrawer=(SlidingDrawer)this.findViewById(R.id.slidingDrawer1);        mImageView=(ImageView)this.findViewById(R.id.handle);                //获取ListView并填充内容        lvNews=(ListView)findViewById(R.id.content);        lvNews.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,a));              //监听打开抽屉事件        mDrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {                        @Override            public void onDrawerOpened() {                // TODO Auto-generated method stub                 mImageView.setImageResource(R.drawable.ic_launcher);              }        });        mDrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {                        @Override            public void onDrawerClosed() {                // TODO Auto-generated method stub                   mImageView.setImageResource(R.drawable.ic_launcher);              }        });    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    }

四、标签组件Tabhost

TabHost的实现有两种方式,第一种继承TabActivity,从TabActivity中用getTabHost()方法获取TabHost。各个Tab中的内容在布局文件中定义就行了。

第二种方式,不继承TabActivity,在布局文件中定义TabHost即可,但是TabWidget的id必须是@android:id/tabs,FrameLayout的id必须是@android:id/tabcontent。

 

第二种方式:布局文件中定义TabHost

activity_main.xml”文件

<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"        android:id="@+id/hometabs"      android:orientation="vertical"      android:layout_width="match_parent"        android:layout_height="match_parent">       <TabHost android:id="@+id/tabhost"           android:layout_width="fill_parent"           android:layout_height="wrap_content">           <LinearLayout              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent">                             <TabWidget android:id="@android:id/tabs"                 android:orientation="horizontal"                android:layout_width="match_parent"                android:layout_height="wrap_content">              </TabWidget>                          <FrameLayout android:id="@android:id/tabcontent"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content">                        <TextView android:id="@+id/text"                          android:layout_width="match_parent"                          android:layout_height="match_parent"                         android:text="第一个选项框"/>                          <TextView android:id="@+id/photo"                          android:layout_width="match_parent"                          android:layout_height="match_parent"                         android:text="第二个选项框"/>                          <TextView android:id="@+id/video"                          android:layout_width="match_parent"                          android:layout_height="match_parent"                         android:text="第三个选项框"/>               </FrameLayout>                      </LinearLayout>      </TabHost>  </LinearLayout>
MainActivity.java”文件
package com.genwoxue.tabhost_b;import android.os.Bundle;import android.app.Activity;import android.widget.TabHost;import android.widget.TabWidget;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          //获取TabHost对象        TabHost tabHost = (TabHost) findViewById(R.id.tabhost);          tabHost.setup();          //获取TabWidget对象        TabWidget tabWidget = tabHost.getTabWidget();        //添加选项框一        tabHost.addTab(tabHost                  .newTabSpec("tab1")                  .setIndicator("文本新闻",getResources().getDrawable(R.drawable.ic_launcher))                  .setContent(R.id.text));          //添加选项框二        tabHost.addTab(tabHost                  .newTabSpec("tab2")                  .setIndicator("图片新闻",getResources().getDrawable(R.drawable.ic_launcher))                  .setContent(R.id.photo));          //添加选项框三        tabHost.addTab(tabHost                  .newTabSpec("tab3")                  .setIndicator("视频新闻",getResources().getDrawable(R.drawable.ic_launcher))                  .setContent(R.id.video));      }}

Android之Composite