java攻城狮之路(Android篇)--widget_webview_metadata_popupwindow_tabhost_分页加载数据_菜单

一、widget:桌面小控件
1 写一个类extends AppWidgetProvider
2 在清单文件件中注册:

<receiver android:name=".ExampleAppWidgetProvider" >
    <intent-filter>
       <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>
    <meta-data android:name="android.appwidget.provider"
               android:resource="@xml/example_appwidget_info" />
</receiver>

3 在res/xml创建example_appwidget_info.xml

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dp"
    android:minHeight="72dp"
    android:initialLayout="@layout/example_appwidget">
</appwidget-provider>

4 指定布局 example_appwidget.xml
生命周期:
1 添加到桌面:
onEnabled() --> onUpdate() //经过测试,4.0以后的版本添加到桌面时不会执行onEnabled()了
2 删除
onDeleted()----> onDisabled() //经过测试,4.0以后的版本删除时不会执行onDisabled()了
如果桌面已经有一个了widget的实例存在,再次添加onUpdate()
删除之后,如果桌面上还有widget的实例存在,只会调用onDeleted().
更成时间的显示:
1 使用一个Servic来执行时间的更新
Timer TimerTask
练习:查看API文档可以根据文档里面的例子来做

package com.shellway.widget;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

}
MainActivity.java
package com.shellway.widget;

import java.text.SimpleDateFormat;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.sax.StartElementListener;
import android.util.Log;
import android.widget.RemoteViews;

public class ExampleAppWidgetProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        // TODO Auto-generated method stub
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        //开启一个实时计时的服务
        Intent intent = new Intent(context,MyService.class);
        context.startService(intent);
        /*RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.wedget);
        long date = java.lang.System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        //给view设置时间
        view.setTextViewText(R.id.tv_timer, time);
        //点击它,要跳转到一个新的界面
        Intent intent = new Intent(context,MainActivity.class);
        PendingIntent pintent = PendingIntent.getActivity(context, 100, intent, 0);
        view.setOnClickPendingIntent(R.id.tv_timer, pintent);
        //更新widget,要放在最后
        appWidgetManager.updateAppWidget(appWidgetIds, view);*/
    }
    
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        // TODO Auto-generated method stub
        super.onDeleted(context, appWidgetIds);
        Log.i("i", "  onDeleted  ");
        //在用户删除掉的时候把服务也停止
        Intent intent = new Intent(context,MyService.class);
        context.stopService(intent);
    }
}
ExampleAppWidgetProvider.java
package com.shellway.widget;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;

public class MyService extends Service {
    
    private Timer timer;
    private TimerTask task = new TimerTask(){
        @Override
        public void run() {
            // TODO Auto-generated method stub
            AppWidgetManager appWidgetManager = AppWidgetManager
                                                .getInstance(getApplicationContext());
            RemoteViews view = new RemoteViews(getPackageName(), R.layout.wedget);
            long date = java.lang.System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(date);
            //给view设置时间
            view.setTextViewText(R.id.tv_timer, time);
            //点击它,要跳转到一个新的界面
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            PendingIntent pintent = PendingIntent.getActivity(getApplicationContext(),
                                                                        100, intent, 0);
            view.setOnClickPendingIntent(R.id.tv_timer, pintent);
            ComponentName provider = new ComponentName(getApplicationContext(), 
                                                       ExampleAppWidgetProvider.class);
            appWidgetManager.updateAppWidget(provider, view);
        }
    };

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        //新建一个计时器
        timer = new Timer();
        //用计时器开启一个任务,计时器产生1秒后开始,每隔一秒更新一次(即:每秒执行一次run方法)
        timer.schedule(task, 1000, 1000);
        
    }
    
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //取消计时器
        timer.cancel();
        task = null;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}
MyService.java
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dp"
    android:minHeight="40dp"
    android:initialLayout="@layout/wedget"
    >
     
</appwidget-provider>
新建在res/xml文件下的example_appwidget.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.shellway.widget.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个widget" />

</RelativeLayout>
布局文件: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"
    android:background="@android:color/white"
     >

    <TextView
        android:id="@+id/tv_timer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textColor="#f00"
        android:text="我是widget"
         />

</LinearLayout>
布局文件:widget.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.widget"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- widget实际上是一个广播接收者BroadcastReceiver -->
        <receiver android:name=".ExampleAppWidgetProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/example_appwidget" />
        </receiver>
        <service  android:name=".MyService"></service>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

二、网页实现界面:webview
1 数据:应该来自于手机本身。
网页资源若放在本地asset目录中则会自动产生一个:file:///android_asset/目录
webview 可以把一个java对象传递给网页,再让javascript去调用这个对象里面的方法
1 onload() javascript 代码调用java代码 java再调用javascript

package com.shellway.htmlui;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.shellway.domain.Contact;
import com.shellway.service.ContactService;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebView;

public class MainActivity extends ActionBarActivity {

    private WebView webview;
    private ContactService service;
    @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    //    requestWindowFeature(Window.FEATURE_NO_TITLE); 设置无标题
        setContentView(R.layout.activity_main);
        webview = (WebView) findViewById(R.id.webview);
        service = new ContactService();
        
        //给webview传递一个对象
        webview.addJavascriptInterface(new ContactPulgin(), "contact");
        //设置webview可以执行JavaScript代码
        webview.getSettings().setJavaScriptEnabled(true);
        //加载网页
        webview.loadUrl("file:///android_asset/index.html");
    }
   
    private class ContactPulgin {
        //网页一加载就会执行onload="javascript:contact.showcontacts()",写方法
        public void showcontacts(){
            try {
                List<Contact> contacts = service.getContact();
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < contacts.size(); i++) {
                    JSONObject jsonObject = new JSONObject();
                    Contact info = contacts.get(i);
                    jsonObject.put("name", info.getName());
                    jsonObject.put("amount", info.getAmount());
                    jsonObject.put("phone", info.getPhone());
                    jsonArray.put(jsonObject);
                }
                String json = jsonArray.toString();
                //给javascript返回一个json数据
                webview.loadUrl("javascript:show("+ json +")");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        
        //实现点击电话号码打电话功能
        public void call(String phone){
            Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phone));
            startActivity(intent);
        }
    }
}
MainActivity.java
package com.shellway.service;

import java.util.ArrayList;
import java.util.List;

import com.shellway.domain.Contact;

public class ContactService {
    //模拟数据
    public List<Contact> getContact(){
        List<Contact> contacts = new ArrayList<Contact>();
        contacts.add(new Contact("李斯", 12000, "13128783361"));
        contacts.add(new Contact("赵高", 10000, "13128783362"));
        contacts.add(new Contact("张良", 15000, "13128783363"));
        contacts.add(new Contact("刘邦", 13000, "13128783364"));
        contacts.add(new Contact("项羽", 17000, "13128783365"));
        return contacts;
    }
}
ContactService.java
package com.shellway.domain;

public class Contact {
      private String name;
      private long amount;
      private String phone;
      
    public Contact(String name, long amount, String phone) {
        super();
        this.name = name;
        this.amount = amount;
        this.phone = phone;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getAmount() {
        return amount;
    }
    public void setAmount(long amount) {
        this.amount = amount;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
    @Override
    public String toString() {
        return "Contact [name=" + name + ", amount=" + amount + ", phone="
                + phone + "]";
    }
      
}
Contact.java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    function show(jsondata){//  [{name:"xxx",amount:600,phone:"13988888"},{name:"bb",amount:200,phone:"1398788"}]
            var jsonobjs = eval(jsondata);
            var table = document.getElementById("personTable");
            for(var y=0; y<jsonobjs.length; y++){
                var tr = table.insertRow(table.rows.length); //添加一行
                //添加三列
                var td1 = tr.insertCell(0);
                var td2 = tr.insertCell(1);
                td2.align = "center";
                var td3 = tr.insertCell(2);
                td3.align = "center";
                //设置列内容和属性
                td1.innerHTML = jsonobjs[y].name; 
                td2.innerHTML = jsonobjs[y].amount; 
                td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].phone+ "\")'>"+ jsonobjs[y].phone+ "</a>"; 
            }
    }
</script>

</head>
<!-- js代码通过webView调用其插件中的java代码 -->
<body onload="javascript:contact.showcontacts()">
   <table border="0" width="100%" id="personTable" cellspacing="0">
        <tr>
            <td width="35%">姓名</td><td width="30%" align="center">存款</td><td align="center">电话</td>
        </tr>
    </table>
    <a href="javascript:window.location.reload()">刷新</a>
</body>

</html>
index.html
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.shellway.htmlui.MainActivity" >

    <WebView 
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

</RelativeLayout>
布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.htmlui"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.CALL_PHONE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

三、安装和卸载应用apk的minetype为:application/vnd.android.package-archive

package com.shellway.install;

import java.io.File;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void install(View view){
        //因为在系统中已经存在安装模块的实现,我们只需激活它就可以了
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        File file = new File(Environment.getExternalStorageDirectory(),"htmlui.apk");
        //文件类型一般可以在tomcat的web.xml配置文件中查找
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
    public void uninstall(View view){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DELETE);
        //卸载应用只需要包名
        intent.setData(Uri.parse("package:com.shellway.htmlui"));
        startActivity(intent);
    }
}
MainActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >

    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="install"
        android:text="安装"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="uninstall"
        android:text="卸载"
        />
</LinearLayout>
activity_mian.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.install"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

四、metadata元数据

package com.shellway.metadata;

import android.support.v7.app.ActionBarActivity;
import android.content.ComponentName;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void get(View view){
         try {
             //得到包管理器,它可以获取四大组件的元数据信息
            PackageManager pm = getPackageManager();
             ComponentName component = new ComponentName(this, MainActivity.class);
             ActivityInfo info = pm.getActivityInfo(component, PackageManager.GET_META_DATA);
             Bundle bundle = info.metaData;
             String name = bundle.getString("name");
             int number = bundle.getInt("number");
             String first = bundle.getString("first");
             String two = getString(bundle.getInt("two"));
             Log.i("i", name);
             Log.i("i", number+"");
             Log.i("i", first);
             Log.i("i", two);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}
MainActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="get"
        android:text="得到数据"
        />

</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.metadata"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <!-- 给activity组件添加一些元数据信息 -->
            <meta-data android:name="name" android:value="骄阳08的博客" />
            <meta-data android:name="number" android:value="08" />
            <meta-data android:name="first" android:value="@string/first" />
            <meta-data android:name="two" android:resource="@string/two" />
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

五、drawble:有一个可以把图片处理成.9.png类型的工具在android-sdk\tools下的draw9patch.bat
1、Layer List:叠代列表,比如相框和相片的关系
2、State List:状态列表,比如不点击是一个状态,点击了又是一个状态
3、Level List:打分效果,比如信号强弱
4、Transition Drawable:移动动画,即从一个动画到什么样的一个动画
5、Inset Drawable:插入图片,比如可以在一张图片周围空余的地方插入另一张图片
6、Clip Drawable:裁剪图片,比如进度条
7、Scale Drawable:拉伸和缩放图片
8、Shape Drawable:通过编码XML文件绘制一张图形,经常用到

package com.shellway.drawable;

import android.support.v7.app.ActionBarActivity;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = (ImageView) findViewById(R.id.iv);
    }
    
    public void reset(View view){
        //得到我们自定义的layerlist对象
//        LayerDrawable layerDrawable = (LayerDrawable) getResources()
//                                       .getDrawable(R.drawable.layerlist);
        //把layerlist对象里面的R.id.user图片替换成我们想要的图片ic_launcher
//        layerDrawable.setDrawableByLayerId(R.id.user, getResources()
//                                       .getDrawable(R.drawable.ic_launcher));
        //替换后再设置回给ImageView
//        iv.setImageDrawable(layerDrawable);
        LevelListDrawable levelList = (LevelListDrawable) iv.getDrawable();        
        levelList.setLevel(20);
        iv.setImageDrawable(levelList);
                                       
    }
}
MainActivity.java
<?xml version="1.0" encoding="utf-8"?>

 <layer-list
     xmlns:android="http://schemas.android.com/apk/res/android" >
     <item
         android:drawable="@drawable/faceback"
          />
     <item
         android:drawable="@drawable/user"
         android:id="@+id/user"
         android:top="68dp"
         android:right="18dp"
         android:bottom="22dp"
         android:left="18dp" />
 </layer-list>
layerlist.xml
<?xml version="1.0" encoding="utf-8"?>
<level-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@drawable/faceback"
        android:maxLevel="10"
        android:minLevel="0" />
    <item
        android:drawable="@drawable/user"
        android:maxLevel="20"
        android:minLevel="10" />
</level-list>
levellist.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 这里注意,有动作条件的代码一定要放在没有条件即正常状态的前面 -->
    <item android:state_pressed="true" android:drawable="@drawable/bg_selected"></item>
    <item android:drawable="@drawable/bg_normal"></item>

</selector>
selector.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 
android:shape="rectangle" 图形的形状,这里是长方形
corners 圆角
gradient 渐变色
padding 内边距
size 图形大小
solid 内填充色,它和gradient只使用一个
stroke 画边虚线的效果
 -->
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="3dp"
         />
    <gradient
        android:startColor="#D0F4F9"
        android:centerColor="#4BED23"
        android:endColor="#5FF2FA"
        />
    <padding
        android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp" />
    <stroke
        android:width="1dp"
        android:color="#00f"
        android:dashWidth="10dp"
        android:dashGap="2dp" />
</shape>
shaplist.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >

    <ImageView 
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/levellist"
        />
    <Button 
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="reset"
        android:text=" 下  一  张    "
        android:background="@drawable/shapelist"
        />

</LinearLayout>
布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.drawable"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

六、泡泡窗口:popupwindow

package com.shellway.popupwindow;

import android.support.v7.app.ActionBarActivity;
import android.graphics.ColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private LayoutInflater inflater;
    private PopupWindow mpPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        inflater = LayoutInflater.from(this);
    }

    public void show(View view){
        View contentView = inflater.inflate(R.layout.popupwindow, null);
        GridView gv = (GridView) contentView.findViewById(R.id.gridview);
        gv.setAdapter(new MyAdapter());
        gv.setOnItemClickListener(new MyOnItemClickListener());
        mpPopupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT, 
                                                      LayoutParams.WRAP_CONTENT);
        //如果需要点击其他的地方popupwindow自动消失: 1 popupwindow必须指定背景   2 poupwindow必须获取焦点
        mpPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mpPopupWindow.setFocusable(true);
        //把它显示在view下面即所点击的按钮下面
        mpPopupWindow.showAsDropDown(view);
    }
    
    private class MyOnItemClickListener implements OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // TODO Auto-generated method stub
            mpPopupWindow.dismiss();
        }
    }
    
    private class MyAdapter extends BaseAdapter{

        private int[] images = new int[]{R.drawable.i1,R.drawable.i2,R.drawable.i3
                ,R.drawable.i4,R.drawable.i5,R.drawable.i6,R.drawable.i7,R.drawable.i8};
        private String[] names = new String[]{"搜索", "文件管理", "下载管理", "全屏"
                                              , "网址", "书签", "加入书签", "分享页面"};
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return images.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return names[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.item, null);
            ImageView iv = (ImageView) view.findViewById(R.id.iv);
            TextView tv = (TextView) view.findViewById(R.id.tv);
            iv.setImageResource(images[position]);
            tv.setText(names[position]);
            return view;
        }
    }
}
MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle">

    <gradient
        android:startColor="#5FF2FA"
        android:endColor="#4BED23"/>
  
</shape>
bg.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="show"
        android:text="显示"
        />

</LinearLayout>
布局文件: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" 
    android:background="@drawable/bg">
    
    <GridView 
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:numColumns="4"
        android:horizontalSpacing="2dp"
        android:verticalSpacing="2dp"
        ></GridView>

</LinearLayout>
布局文件:opupwindow.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" >
    
    <ImageView 
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        />
    <TextView 
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        />

</LinearLayout>
布局文件:item.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.popupwindow"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

七、tabhost标签页、自定义标签页

package com.shellway.tabhost;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private TabHost tb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tb = (TabHost) findViewById(R.id.tabhost);
        tb.setup();//找到tabwidget 、 FrameLayout
        
        TabSpec tab1 = tb.newTabSpec("tab1");
        //指定标签
    //    tab1.setIndicator("首页", getResources().getDrawable(R.drawable.i1));
        tab1.setIndicator(createView("首页", R.drawable.i1));//指定标签
        tab1.setContent(R.id.line1);//指定标签页的内容
        tb.addTab(tab1);
        
        TabSpec tab2 = tb.newTabSpec("tab2");
        //指定标签
    //    tab2.setIndicator("第二页", getResources().getDrawable(R.drawable.i2));
        tab2.setIndicator(createView("第二页", R.drawable.i2));//指定标签
        tab2.setContent(R.id.line2);//指定标签页的内容
        tb.addTab(tab2);
        
        TabSpec tab3 = tb.newTabSpec("tab3");
        //指定标签
    //    tab3.setIndicator("第三页", getResources().getDrawable(R.drawable.i7));
        tab3.setIndicator(createView("第三页", R.drawable.i7));//指定标签
        tab3.setContent(R.id.line3);//指定标签页的内容
        tb.addTab(tab3);
        
    }
    
    //创建一个View返回
    public View createView(String name,int image){
        View view = View.inflate(this, R.layout.tab, null);
        ImageView iv_title = (ImageView) view.findViewById(R.id.iv_tile);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        iv_title.setImageResource(image);
        tv_title.setText(name);
        return view;
    }

    
}
MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_selected="true" android:drawable="@drawable/bg_selected"></item>
    <item android:drawable="@drawable/bg_normal"></item>

</selector>
selector.xml
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tabhost"
    android:orientation="vertical"
     >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        <TabWidget 
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
        <FrameLayout 
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            >
      <LinearLayout 
          android:id="@+id/line1"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:background="@android:color/darker_gray"
          >
            <TextView 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="首页"
            />
      </LinearLayout>
      <LinearLayout 
          android:id="@+id/line2"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:background="@android:color/darker_gray"
          >
            <TextView 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="第二页"
            />
      </LinearLayout>
      <LinearLayout 
          android:id="@+id/line3"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:background="@android:color/darker_gray"
          >
            <TextView 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="第三页"
            />
        </LinearLayout>
      </FrameLayout>
    </LinearLayout>
    
</TabHost>
布局文件: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" 
    android:background="@drawable/selector">
    <ImageView 
        android:id="@+id/iv_tile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/i1"
        />
    <TextView 
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="首页"
        />
</LinearLayout>
布局文件:tb.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.tabhost"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

八、数据量多:分页加载数据

package com.shellway.pageloaddata;

import java.util.ArrayList;
import java.util.List;

import com.shellway.service.DataService;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {
    private static final int FINISH_GET_DATA = 0;
    private ListView lv_data;
    private List<String> data;//加载的总数据
    private DataService service;
    private ArrayAdapter<String> adapter;
    private View footer;
    private boolean finish = true;//是否加载完成的标志
    
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case FINISH_GET_DATA:
                ArrayList<String> result = (ArrayList<String>) msg.obj;
                data.addAll(result);
                adapter.notifyDataSetChanged();//让listview自动刷新
                finish = true;
                if (lv_data.getFooterViewsCount()>0) {
                    lv_data.removeFooterView(footer);
                }
                break;

            default:
                break;
            }
        };
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        lv_data = (ListView) findViewById(R.id.lv_data);
        service = new DataService();
        data = new ArrayList<String>();
        List<String> result = service.getData(1, 20);
        data.addAll(result);
        adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tv_data, data);
        
        footer = View.inflate(this, R.layout.footer, null);
        //在这里先给适配器声明说我要添加页脚,然后为了不让一开始就有添加的页脚存在我们先除去页脚
        lv_data.addFooterView(footer);
        lv_data.setAdapter(adapter);
        lv_data.removeFooterView(footer);
        //给listview设置滑动事件
        lv_data.setOnScrollListener(new MyOnScrollListener());
    }
    
    private class MyOnScrollListener implements OnScrollListener{
        int totalPage = 5;//设定加载的总页数
        final int pageSize = 20;//设定每页加载20条数据
        
        //scrollState:表示滑动状态  1表示开始滑动、2表示正在滑动、0表示停止滑动
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub
        }

        /**
         * firstVisibleItem:表示当前可见页面的起始数据(即最上面一条)
         * visibleItemCount:表示当前手机窗口可以显示的总共数据条数
         * totalItemCount:表示已经加载的总共数据条数
         */
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            
            //已经滑动完的总共条数
            final int totalCount = firstVisibleItem + visibleItemCount;
            int currentPage = totalCount/pageSize;//当时是第几页
            int nextPage = currentPage + 1;//下一页的页数
            //判断是否已经移动到了listview的最后
            if (totalCount == totalItemCount&&nextPage <= totalPage&&finish) {
                finish = false;
                //添加页脚
                lv_data.addFooterView(footer);
                new Thread(){
                    @Override
                    public void run() {
                        SystemClock.sleep(3000);//模拟网络延迟,睡3秒
                        List<String> data = service.getData(totalCount+1, pageSize);
                        Message msg = new Message();
                        msg.what = FINISH_GET_DATA;
                        msg.obj = data;
                        handler.sendMessage(msg);
                    }
                }.start();
            }
        }
    }
}
MainActivity.java
package com.shellway.service;

import java.util.ArrayList;
import java.util.List;

public class DataService {
     //加载数据
     public List<String> getData(int startData,int pageSize){
         int length = startData + pageSize;
         List<String> list = new ArrayList<String>();
         for (int i = startData; i < length; i++) {
            String data = new String("分页加载的数据:数据"+i);
            list.add(data);
        }
         return list;
     }
}
DataService.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/abc_search_url_text_normal"
    android:orientation="vertical"
     >

    <ListView 
        android:id="@+id/lv_data"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></ListView>

</LinearLayout>
布局文件: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="wrap_content"
    android:orientation="horizontal" >
    <ProgressBar 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:textSize="20dp"
        android:text="数据正在加载中。。。。"
        />

</LinearLayout>
布局文件footer.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" >
    <TextView 
        android:id="@+id/tv_data"
        android:layout_width="match_parent"
        android:layout_height="26dp"
        android:layout_marginLeft="5dp"
        android:textSize="20dp"
        />

</LinearLayout>
布局文件:item.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.pageloaddata"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

九、快捷图标的创建和删除
可以参考Android源码中的apps\Launcher2\AndroidManifest.xml文件,它对应的数据库表为:launcher.db

package com.shellway.shortcut;

import android.support.v7.app.ActionBarActivity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void create(View view){
        if (isExist()) {
            Toast.makeText(this, "快捷方式已经存在", 1).show();
        }else{
            Intent intent = new Intent();
            intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
            //设置快捷方式的名称
            intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式");
            //设置快捷方式的图标
            Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.main_icon);
            intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
            //设置快捷方式要要激活的应用
            Intent i = new Intent();
            i.setAction(Intent.ACTION_MAIN);
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            i.setComponent(new ComponentName(this, MainActivity.class));
            intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, i);
            //发出广播
            sendBroadcast(intent);
        }
    }
    
    //检查快捷方式是否已经存在
    public boolean isExist(){
        Uri uri  = null;
        //添加兼容性
        if (getSDKVersion()<8) {//8代表2.2以下版本,而在2.2版本以前是launcher,之后才是launcher2
            uri = Uri.parse("content://com.android.launcher.settings/favorites");
        }else{
            uri = Uri.parse("content://com.android.launcher2.settings/favorites");
        }
        
        boolean flag = false;
        Cursor c = getContentResolver().query(uri, null, "title=?", new String[]{"快捷方式"}, null);
        if (c.moveToNext()) {
            flag = true;
        }
        c.close();
        return flag;
    }
    
    //得到SDK版本信息
    public int getSDKVersion(){
        return android.os.Build.VERSION.SDK_INT;
    }
    
    //删除快捷方式
    public void delete(View view){
        Intent intent = new Intent();
        intent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
        //设置快捷方式的名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式");
        //设置快捷方式的图标
        Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.main_icon);
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        //设置快捷方式要要激活的应用
        Intent i = new Intent();
        i.setAction(Intent.ACTION_MAIN);
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        i.setComponent(new ComponentName(this, MainActivity.class));
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, i);
        //发出广播
        sendBroadcast(intent);
    }
    
}
MainActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >

    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="create"
        android:text="创建快捷图标"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="delete"
        android:text="删除快捷图标"
        />

</LinearLayout>
布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.shortcut"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
    <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
    <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

十、菜单的创建和上下文菜单

1、普通菜单:布局文件实现和代码实现两种方式

package com.shellway.menu;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;

import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    private static final int MENU_NEW = 0;
    private static final int MENU_DELETE = 1;
    private static final int SUBMENU = 3;
    private static final int SUBMENU1 = 4;
    private static final int SUBMENU2 = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //编码方式创建菜单
/*        menu.add(0, MENU_NEW, 0, "新建");
        menu.add(0, MENU_DELETE, 0, "删除");
        SubMenu  subMenu = menu.addSubMenu("子菜单");
        SubMenu subMenu1 = subMenu.addSubMenu(0, SUBMENU1, 0, "子菜单1");
        SubMenu subMenu2 = subMenu.addSubMenu(0, SUBMENU2, 0, "子菜单2");*/
        //这里使用布局文件创建菜单代替编码方式
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //给菜单添加点击事件
        int id = item.getItemId();
        switch (id) {
        case MENU_NEW:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;
        case MENU_DELETE:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;
        case SUBMENU1:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;
        case SUBMENU2:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;

        default:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;
        }
        return super.onOptionsItemSelected(item);
    }
}
MainActivity.java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.shellway.menu.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>
布局文件:activity_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.shellway.menu.MainActivity" >

    <item
        android:id="@+id/menu_new"
        android:title="新建立"
        />
    <item
        android:id="@+id/menu_delete"
        android:title="删除"
        />
    
    <item
        android:id="@+id/submenu"
        android:title="子菜单"
        >
            <menu>
                <item
                android:id="@+id/submenu1"
                android:title="子菜单1"
                />
                <item
                android:id="@+id/submenu2"
                android:title="子菜单2"
                />
            </menu>
      </item>
      
</menu>
menu目录下的菜单文件:main.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.menu"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

2、上下文菜单:实现复制号码到拨号盘、发送短信、复制电话号码到剪切板

package com.shellway.contextmenu;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog.Calls;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private static final int COPY_NUMBERTO_ID = 0;
    private static final int SEND_SMS_ID = 1;
    private static final int COPY_NUMBER_ID = 2;
    private ListView listview;
    private CursorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        listview = (ListView) findViewById(R.id.listview);
        //查询联系人表获得联系人电话号码
        Cursor c = getContentResolver().query(Calls.CONTENT_URI, new String[]{Calls._ID,Calls.NUMBER}
                                                    , null, null, null);
        adapter = new MyCursorAdapter(this, c);
        //如果数据是来自于手机本省的数据库,就使用CursorAdpater的子类
        listview.setAdapter(adapter);
        //注册上下文菜单
        registerForContextMenu(listview);
        
    }
    
    //创建一个上下文菜单
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        menu.add(0, COPY_NUMBERTO_ID, 0, "复制电话号码到拨号盘");
        menu.add(0, SEND_SMS_ID, 0, "发送短信");
        menu.add(0, COPY_NUMBER_ID, 0, "复制电话号码");
        super.onCreateContextMenu(menu, v, menuInfo);
    }
    
    //给上下文菜单添加点击事件
    @SuppressLint("NewApi")
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        int id = item.getItemId();
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        Cursor c = (Cursor) adapter.getItem(position);
        String number = null;
        if (c.moveToNext()) {
            number = c.getString(c.getColumnIndex(Calls.NUMBER));
        }
        Intent intent = null;
        switch (id) {
        case COPY_NUMBERTO_ID:
            intent = new Intent();
            intent.setAction(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + number));
            startActivity(intent);
            break;
            
        case SEND_SMS_ID:
            intent = new Intent();
            intent.setAction(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("smsto:" + number));
            startActivity(intent);
            break;
            
        case COPY_NUMBER_ID:
            //得到剪贴板服务
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            cm.setPrimaryClip(ClipData.newPlainText("number", number));
            break;
        default:
            break;
        }
        
        return super.onContextItemSelected(item);
    }
    
    private class MyCursorAdapter extends CursorAdapter{

        public MyCursorAdapter(Context context, Cursor c) {
            super(context, c);
            // TODO Auto-generated constructor stub
        }

        //创建item的布局
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // TODO Auto-generated method stub
            TextView tv = new TextView(context);
            tv.setTextSize(22);
            //tv.setBackgroundColor(getResources().getColor(R.color.color));
            tv.setBackgroundColor(Color.LTGRAY);
            tv.setTextColor(Color.BLACK);
            return tv;
        }

        //把数据与控件绑定
        public void bindView(View view, Context context, Cursor cursor) {
            // TODO Auto-generated method stub
            String number = cursor.getString(cursor.getColumnIndex(Calls.NUMBER));
            TextView tv = (TextView) view;
            tv.setText(number);
        }
    }
}
MainActivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >
    <ListView 
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        ></ListView>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.contextmenu"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
    <uses-permission android:name="android.permission.READ_CALL_LOG"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

上下文菜单一般是针对ListView(多条数据的操作)

十一、反编译
反编译的步骤:
1 apktool1.4.1.tar.bz2 apktool-install-windows-r04-brut1.tar.bz2 dex2jar-0.0.7.11-SNAPSHOT.zip jd-gui.cfg 工具
2 解压上面的工具
3 把apktool1.4.1.tar.bz2解压出来的apktool.jar复制到apktool-install-windows-r04-brut1.tar.bz2目录
4 放置一个xxx.apk到apktool-install-windows-r04-brut1目录
cd /d C:\tools\apktool-install-windows-r04-brut1
apktool.bat d -s taskman_2.apk 生成一个taskman_2的文件夹
5 把classes.dex复制到C:\tools\dex2jar-0.0.7.11-SNAPSHOT\dex2jar-0.0.7.11-SNAPSHOT
cd /d C:\tools\dex2jar-0.0.7.11-SNAPSHOT\dex2jar-0.0.7.11-SNAPSHOT
dex2jar.bat classes.dex 生成 classes_dex2jar.jar
6 通过jd-gui.cfg工具查看classes_dex2jar.jar

 

posted @ 2015-01-01 20:25  骄阳08  阅读(974)  评论(0编辑  收藏  举报