Android 桌面部件 Widget 實現待辦清單
阿新 • • 發佈:2018-12-11
效果圖
原始碼
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();
}
});