文章目录
效果图
源码
https://download.csdn.net/download/sgamble/10682426
1. 声明 Widget 的属性
在 res 新建 xml 文件夹,创建一个 my_app_widget_info.xml 的文件。
如果 res 下没有 xml 文件,则先创建。
my_app_widget_info.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialKeyguardLayout="@layout/my_app_widget"
android:initialLayout="@layout/my_app_widget"
android:minHeight="40dp"
android:minWidth="40dp"
android:previewImage="@drawable/example_appwidget_preview"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="86400000"
android:widgetCategory="home_screen">
</appwidget-provider>
android:minWidth : 最小宽度
android:minHeight : 最小高度
android:updatePeriodMillis : 更新widget的时间间隔(ms),"86400000"为1个小时,值小于30分钟时,会被设置为30分钟。可以用 service、AlarmManager、Timer 控制。
android:previewImage : 预览图片,拖动小部件到桌面时有个预览图
android:initialLayout : 加载到桌面时对应的布局文件
android:resizeMode : 拉伸的方向。horizontal表示可以水平拉伸,vertical表示可以竖直拉伸
android:widgetCategory : 被显示的位置。home_screen:将widget添加到桌面,keyguard:widget可以被添加到锁屏界面。
android:initialKeyguardLayout : 加载到锁屏界面时对应的布局文件
格数 | dp |
---|---|
1 | 40 |
2 | 110 |
3 | 180 |
4 | 250 |
n | 70*n-30 |
2. 创建 layout 布局文件
Widget 主界面布局
my_app_widget.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/widget_margin">
<Button
android:id="@+id/btn_jump"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Jump" />
<ListView
android:id="@+id/listView1"
android:layout_below="@+id/btn_jump"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
列表子项布局
layout_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_below="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageView
android:id="@+id/del"
android:background="@mipmap/ic_launcher"
android:layout_alignParentRight="true"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
跳转后的主界面布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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.test.widgetdemo.MainActivity">
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<Button
android:id="@+id/btn_add"
android:layout_below="@+id/et"
android:text="Add"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
3. 创建 MyAppWidget.java
package com.test.widgetdemo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import static android.R.attr.action;
import static android.R.attr.cacheColorHint;
import static android.content.ContentValues.TAG;
/**
* ====================== AppWidget ========================
* @author SGamble
*/
public class MyAppWidget extends AppWidgetProvider {
private static final String TAG = "MyWidget";
RemoteViews remoteViews;
/**
* package
*/
static ComponentName getComponentName(Context context) {
return new ComponentName(context, MyAppWidget.class);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.e(TAG, "onUpdate");
//设置 ListView
setListView(context, appWidgetManager, appWidgetIds);
//获取 RemoteViews
remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_app_widget);
//绑定id - 按钮点击事件
remoteViews.setOnClickPendingIntent(R.id.btn_jump, getJumpPendingIntent(context)); //跳转到主界面
//发送 del.com 的广播
sendDelIntentBroadcast(context);
//更新widget
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
/**
* 设置 ListView
* @author Gamble
*/
private void setListView(Context context, AppWidgetManager awm, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
Intent intent = new Intent(context, MyWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_app_widget);
views.setRemoteAdapter(R.id.listView1, intent);
awm.updateAppWidget(appWidgetId, views); //设置适配器
awm.notifyAppWidgetViewDataChanged(appWidgetId, R.id.listView1); //通知数据更新
}
}
/**
* 发送 del.com 的广播
* @author Gamble
*/
private void sendDelIntentBroadcast(Context context) {
Intent intent = new Intent("del.com");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 220, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setPendingIntentTemplate(R.id.listView1, pendingIntent);
}
/**
* 点击按钮跳转到指定 Activity
* @author Gamble
*/
private PendingIntent getJumpPendingIntent(Context context) {
Intent skipIntent = new Intent(context, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 200, skipIntent, PendingIntent.FLAG_CANCEL_CURRENT);
return pi;
}
/**
* 接收到任意广播时触发
* -- 广播需要在 清单 文件中设置响应
* <intent-filter>
* <action android:name="add.com"/>
* </intent-filter>
* @author Gamble
*/
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
switch (intent.getAction()){
case "add.com":
Log.e(TAG, "接收到MainActivity传递过来的广播 - 添加操作");
break;
case "del.com": //删除
delEvent(context,intent);
break;
}
updateListView(context,intent); //更新操作
}
/**
* 删除点击的事项
* @author Gamble
*/
private void delEvent(Context context,Intent intent) {
Bundle extras = intent.getExtras();
int position = extras.getInt("key");
Data.del(position);
}
/**
* 更新操作
* - ListView中数据发生改变
* @author Gamble
*/
private void updateListView(Context context,Intent intent) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_app_widget);
final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
final ComponentName cn = new ComponentName(context, MyAppWidget.class);
mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.listView1);
mgr.updateAppWidget(cn, remoteViews);
}
}
4.创建 MyWidgetService.java
package com.test.widgetdemo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import java.util.List;
import static com.test.widgetdemo.Data.getLst;
/**
* ====================== WidgetService ========================
*
* @author SGamble
*/
public class MyWidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new MyWidgetFactory(getApplicationContext(), intent);
}
public static class MyWidgetFactory implements RemoteViewsFactory {
private Context mContext;
private List<String> lst; //列表数据
public MyWidgetFactory(Context context, Intent intent) {
mContext = context;
lst = getLst(); //获取列表
}
@Override
public RemoteViews getViewAt(int position) {
if (position < 0 || position >= getCount()) {
return null;
}
RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.layout_item);
views.setTextViewText(R.id.textView1, lst.get(position));//设置 ListView 的显示
views.setOnClickFillInIntent(R.id.del, delIntent(position));//ListView - item 点击事件
return views;
}
/**
* 删除Intent
* @author Gamble
*/
private Intent delIntent(int position) {
Bundle extras = new Bundle();
extras.putInt("key", position); //传递数据 - item - position
Intent delIntent = new Intent();
delIntent.setAction("del.com"); //设置意图
delIntent.putExtras(extras); //放入需要传递的数据
return delIntent;
}
@Override
public int getCount() {
return lst.size();
}
@Override
public long getItemId(int position) {
return position;
}
/**
* 在调用getViewAt的过程中,显示一个LoadingView。
* 如果return null,那么将会有一个默认的loadingView
* @author Gamble
*/
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public void onCreate() { }
@Override
public void onDataSetChanged() { }
@Override
public void onDestroy() { }
}
}
6.跳转后的界面操作
Button btn = (Button)findViewById(R.id.btn_add);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.et);
Data.addLst(et.getText().toString()); //数据添加
//添加待办事项 - Intent
Intent intent = new Intent("add.com");
sendBroadcast(intent); //发送 add.com 的广播
finish();
}
});