widget支持任何自定义view

一、需要一个加载我们需要自定义view的容器,具有RemoteView的属性,这个容器的代码如下:

package android.widget;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Binder;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.RemotableViewMethod;
import android.view.View;
import android.widget.RemoteViews.RemoteView;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;

@RemoteView
public class ThemeLayout extends FrameLayout {
    private static final String TAG = "ThemeLayout";

    private String mCurrentTheme = null;

    public ThemeLayout(Context context) {
        super(context);
    }

    public ThemeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ThemeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @RemotableViewMethod
    public void setThemePath(String themePath) {
        if (TextUtils.isEmpty(themePath)) {
            Log.e(TAG, "theme path is empty!!!");
            return;
        }
        File file = new File(themePath);
        if (!file.exists()) {
            Log.e(TAG, "theme file is not exist!!!");
            return;
        }

        if (themePath.equals(mCurrentTheme)) {
            return;
        }

        long token = Binder.clearCallingIdentity();
        Context theme = new ExternalContext(getContext(), themePath);
        View childView = applyTheme(theme);
        if (childView != null) {
            removeAllViews();
            addView(childView);
            mCurrentTheme = themePath;
        }
        Binder.restoreCallingIdentity(token);
    }

    private View applyTheme(Context context) {
        try {
            Class cls = context.getClassLoader().loadClass("com.test.utils.DexUtils");
            Object object = cls.newInstance();
            Method method = cls.getMethod("getWidgetLayoutId");
            int layoutId = (int) method.invoke(object);
            if (layoutId > 0) {
                return LayoutInflater.from(getContext()).cloneInContext(context).inflate(layoutId, null);
            } else {
                Log.v(TAG, "layout is not exists");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        } catch (InflateException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static class ExternalContext extends ContextWrapper {

        private Resources mThemeResource;
        private DexClassLoader mThemeClassLoader;
        private Resources.Theme mTheme;

        public ExternalContext(Context base, String themePath) {
            super(base);
            mThemeClassLoader = new DexClassLoader(themePath, getDir("dex", MODE_PRIVATE).getAbsolutePath(), null, getClassLoader());
            AssetManager assetManager = new AssetManager();
            assetManager.addAssetPath(themePath);
            mThemeResource = new Resources(assetManager, super.getResources().getDisplayMetrics(), super.getResources().getConfiguration());
        }

        @Override
        public Resources getResources() {
            return mThemeResource;
        }

        @Override
        public ClassLoader getClassLoader() {
            return mThemeClassLoader;
        }

        @Override
        public Resources.Theme getTheme() {
            if (mTheme == null) {
                mTheme = mThemeResource.newTheme();
                mTheme.setTo(super.getTheme());
            }
            return mTheme;
        }

        public void close() {
            mThemeResource.getAssets().close();
        }
    }
}

容器代码很简单,需要注意的是Class cls = context.getClassLoader().loadClass("com.test.utils.DexUtils"); DexUtils.java这个类就是用于加载view的入口,会在widget中实现。

接下来需要编译framework,因增加了一个新的view,需要到源码根目录执行make update-api命令,再到framework/base/core目录进行编译,使用mm或者mma命令即可。

二、新建一个widget项目

1、WidgetTest.java的代码如下:
package com.test.widgettest;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

/**
 * Created by Andre.Ou on 2018/12/6.
 */

public class WidgetTest extends AppWidgetProvider {

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        RemoteViews views = loadRemoteVies(context);
        if (appWidgetIds != null) {
            appWidgetManager.updateAppWidget(appWidgetIds, views);
        } else {
            appWidgetManager.updateAppWidget(new ComponentName(context, WidgetTest.class), views);
        }
    }

    private RemoteViews loadRemoteVies(Context context) {
        String packagePath = context.getPackageResourcePath();//应用自身的路径
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setString(R.id.themeLayout, "setThemePath", packagePath);
        return views;
    }
}

widget部分主要是将要加载的view所在apk路径通过容器ThemeLayout的setThemePath方法传入,进而加载到容器中

2、widget_layout.xml布局文件如下:





调用容器ThemeLayout的布局、

三、容器访问自定义view的入口

1、定义DexUtils.java类作为入口,代码如下:
package com.test.utils;
import com.test.widgettest.R;

public class DexUtils {

    public int getWidgetLayoutId() {
        return R.layout.cust_layout;
    }
}

cust_layout.xml里面就可以放你任意的自定义view了。

2、cust_layout.xml实例:



    

功能已完成,有不明白的小伙伴请留言。

你可能感兴趣的:(android)