美文网首页
安卓第一课

安卓第一课

作者: 我是上帝可爱多 | 来源:发表于2017-09-04 14:17 被阅读24次

最近我在学习安卓,有些人肯定觉得我疯了,但是我觉得作为一个从java web转作前端的人,如果没有好好搞一下安卓确实说不过去,而且前端和安卓的定位也是一样的嘛,都是构建用户页面和处理交互的,所以今天就带大家走进安卓的世界。

1 ListView

在布局文件中加入一个ListView控件。

<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="
http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent"    
 android:layout_height="fill_parent"> <!-- 添加一个ListView控件 --> <ListView
    android:id="@+id/lv"     android:layout_width="fill_parent"     android:layout_height="fill_parent"/>          
  </LinearLayout>

然后在Activity中初始化

public class listView extends Activity{
    private static final String[] str = new String[] {
    "first", "second", "third", "fourth", "fifth"
    };//定义一个String数组用来显示ListView的内容private ListView lv;/** Called 

    @Override
publicvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView lv = (ListView) findViewById(R.id.lv);//得到ListView对象的引用 /*为ListView设置Adapter来绑定数据*/ 
        lv.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, strs));
    }
} 

提供一下代码 给大家选择

lv.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_checked, strs));
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

lv.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice, strs));
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

在前面讲到过,ListView的职责除了填充数据外,还要处理用户的操作。通过如下的代码就可以为ListView绑定一个点击监听器,点击后在标题栏显示点击的行数。

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            publicvoid onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                    //点击后在标题上显示点击了第几行                    
                    setTitle("你点击了第"+arg2+"行");
            }
        });

很多时候需要在列表中展示一些除了文字以外的东西,比如图片等。这时候可以使用SimpleAdapter。SimpleAdapter的使用也非常简单,同时它的功能也非常强大。可以通过它自定义ListView中的item的内容,比如图片、多选框等。看一个例子,实现一个每一行都有一个ImageView和TextView的ListView。

<?xmlversion="1.0"encoding="utf-8"?>
 <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_height="fill_parent" android:layout_width="fill_parent"> 
<ImageViewandroid:layout_alignParentRight="true" android:layout_width="wrap_content"
 android:layout_height="wrap_content" android:id="@+id/ItemImage"/> 

<TextViewandroid:id="@+id/ItemTitle" android:layout_height="wrap_content" 
android:layout_width="fill_parent" android:textSize="20sp"/>

 <TextViewandroid:id="@+id/ItemText" android:layout_height="wrap_content" 
android:layout_width="fill_parent" android:layout_below="@+id/ItemTitle"/> </RelativeLayout>

配置完毕,就可以在Java代码中为ListView绑定数据。

publicclass MyListViewSimple extends Activity {
    
    private ListView lv;
  
   @Override
   public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lv = (ListView) findViewById(R.id.lv);
        /*定义一个动态数组*/          
       ArrayList<HashMap<String, Object>> listItem = 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.icon);//加入图片            map.put("ItemTitle", "第"+i+"行");  
            map.put("ItemText", "这是第"+i+"行");  
            listItem.add(map);  
        } 

      SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,//需要绑定的数据                
R.layout.item,//每一行的布局//动态数组中的数据源的键对应到定义布局的View中new String[] {"ItemImage"
,"ItemTitle", "ItemText"},   
newint[] {R.id.ItemImage,R.id.ItemTitle,R.id.ItemText}  
            );

         lv.setAdapter(mSimpleAdapter);
         lv.setOnItemClickListener(new 
            OnItemClickListener() {
               @Override
                publicvoid onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                setTitle("你点击了第"+arg2+"行");//设置标题栏显示点击的行                
            }
        });
    }
}

当系统开始绘制ListView的时候,首先调用getCount()方法。得到它的返回值,即ListView的长度。然后系统调用getView()方法,根据这个长度逐一绘制ListView的每一行。也就是说,如果让getCount()返回1,那么只显示一行。而getItem()和getItemId()则在需要处理和取得Adapter中的数据时调用。那么getView如何使用呢?如果有10000行数据,就绘制10000次?这肯定会极大的消耗资源,导致ListView滑动非常的慢,那应该怎么做呢?通过一个例子来讲解如何在使用BaseAdapter的时候优化ListView的显示。例子中将上一节中的ImageView换成Button,并且处理Button的点击事件,其中对ListView的显示做了优化。

publicclass MyListViewBase extends Activity {
     private ListView lv;
     ArrayList<HashMap<String, Object>>listItem; 

    @Override
    publicvoid onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         lv = (ListView) findViewById(R.id.lv);
         MyAdapter mAdapter = new MyAdapter(this);
         lv.setOnItemClickListener(new OnItemClickListener() {

     @Override
     publicvoid onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
        Log.v("MyListViewBase", "你点击了ListView条目" + arg2);//在LogCat中输出信息                
            }
        });
     }

     private ArrayList<HashMap<String, Object>> getDate(){
           ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String,     Object>>();
           for(int i=0;i<30;i++)  
            {  
             HashMap<String, Object> map = new HashMap<String, Object>();  
             map.put("ItemTitle", "第"+i+"行");  
             map.put("ItemText", "这是第"+i+"行");  
             listItem.add(map);  
         } 
        return listItem;
    
    }
     
    private class MyAdapter extends BaseAdapter {
       private LayoutInflater mInflater;
       public MyAdapter(Context context) {
             this.mInflater = LayoutInflater.from(context);
        }

       public View getView(finalint position, View convertView, ViewGroup parent) {
             ViewHolder holder;

             Log.v("MyListViewBase", "getView " + position + " " + convertView);
             if (convertView == null) {
                     convertView = mInflater.inflate(R.layout.item,null);
                     holder = new ViewHolder();
                    holder.title = (TextView) convertView.findViewById(R.id.ItemTitle);
                    holder.text = (TextView) convertView.findViewById(R.id.ItemText);
                    holder.bt = (Button) convertView.findViewById(R.id.ItemButton);
                    convertView.setTag(holder);//绑定ViewHolder对象                   }
        else{
                    holder = (ViewHolder)convertView.getTag();       
        }
        
            holder.title.setText(getDate().get(position).get("ItemTitle").toString());
            holder.text.setText(getDate().get(position).get("ItemText").toString());
            
           holder.bt.setOnClickListener(new OnClickListener() {
                
                @Override
                publicvoid onClick(View v) {
                Log.v("MyListViewBase", "你点击了按钮" + position);                           
                }
            });
            
            return convertView;
        }
    
    }
      public final class ViewHolder{
            public TextView title;
            public TextView text;
            public Button   bt;
    }
}

2 LayoutInflater

假设root 的xml文件为layout_root,待infalte的xml文件为layout_child:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_root"
    android:orientation="vertical"
    android:layout_width="300dp"
    android:layout_height="400dp"
    android:background="@color/forestgreen"
>
<TextView
    android:id="@+id/tv_root_ll"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="LL and root"
    android:layout_gravity="center_horizontal"
    android:textSize="20sp"
    />
</LinearLayout>

layout_child:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_child"
    android:orientation="vertical"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="@color/violet"
    >
    <TextView
        android:id="@+id/tv_child_ll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LL and child"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        />
</LinearLayout>

 private void caseOne(){
    childView = inflater.inflate(R.layout.layout_child, null);
    setContentView(childView);
}

这种情况,渲染的child视图,没有view group, 所以他的layout height 和 width都不起作用,自动为match_parent.

private void caseTwo(){
  rootView = (ViewGroup)inflater.inflate(R.layout.layout_root,null);
  childView = inflater.inflate(R.layout.layout_child, rootView, false);
  setContentView(childView);
}

这个时候有rootview,所以layout_width 和 height起作用。

private void caseThree(){
  rootView = (ViewGroup)inflater.inflate(R.layout.layout_root,null);
  childView = inflater.inflate(R.layout.layout_child, rootView, true);
  setContentView(childView);
}

相关文章

网友评论

      本文标题:安卓第一课

      本文链接:https://www.haomeiwen.com/subject/lehtjxtx.html