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布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<android.widget.ThemeLayout
    android:id="@+id/themeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.widget.ThemeLayout>

调用容器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实例:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.test.widgettest.CustomView
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值