在Launcher3中增加主题切换功能

说明,在SD卡中放入theme_thumbs文件夹,里面存放主题风格的缩略图,然后在theme文件下存放主题的资源文件,例如/theme/sport等等,里面图标命名规则是主题KEY_

加上快捷方式的类名(下划线取代点),例如sport_com_android_browser_BrowserActivity.png,这样就可以自动扫描加载主题风格了。

1  \packages\apps\Launcher3\res\layout\theme_picker.xml

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
<GridView  
  xmlns:android="http://schemas.android.com/apk/res/android"  
  android:id="@+id/gridview"  
  android:layout_width="fill_parent"  
  android:layout_height="fill_parent"  
  android:columnWidth="280dp"  
  android:numColumns="auto_fit"  
  android:horizontalSpacing="10dp"  
  android:verticalSpacing="10dp"  
  android:stretchMode="columnWidth"  
  android:gravity="center">  
</GridView>
</LinearLayout>


2  packages\apps\Launcher3\src\com\android\launcher3\ThemePickerActivity.java

package com.android.launcher3;


import android.app.Activity;
import java.util.ArrayList; 
import java.util.List; 
import android.content.Context; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.TextView;
import java.io.File;
import android.graphics.Bitmap;
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.os.Bundle;
import android.widget.AdapterView;
import android.app.WallpaperManager;
import android.graphics.BitmapFactory;

public class ThemePickerActivity extends Activity {
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.theme_picker); 
        getThemeBitmaps("mnt/sdcard/theme_thumbs");
        GridView gridView=(GridView)findViewById(R.id.gridview);  
        gridView.setAdapter(new ImageAdapter(this));  
        gridView.setOnItemClickListener(new OnItemClickListener() {  

  @Override  
            public void onItemClick(AdapterView<?> parent, View view,  
                    int position, long id) {
System.out.println("mThemesNames.size() -- " + mThemesNames.size());
WallpaperManager wallpaperManager = WallpaperManager.getInstance(ThemePickerActivity.this);
if(position == mThemesNames.size()) {
getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
                Context.MODE_PRIVATE).edit().putString("theme_key","default").commit();
try{
wallpaperManager.setResource(android.content.res.Resources.getSystem().getIdentifier("default_wallpaper", "drawable", "android"));
}catch (Exception e){
e.printStackTrace();
}
android.os.Process.killProcess(android.os.Process.myPid());
}

else  if( isFileEffect("mnt/sdcard/theme/"+mThemesNames.get(position)) ){
getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
               Context.MODE_PRIVATE).edit().putString("theme_key",mThemesNames.get(position)).commit();
try{
wallpaperManager.setBitmap(BitmapFactory.decodeFile("mnt/sdcard/theme/"+mThemesNames.get(position)+"/"+mThemesNames.get(position)+"_wallpaper.jpg" ));
}catch (Exception e){
e.printStackTrace();
}
android.os.Process.killProcess(android.os.Process.myPid());
            }else{
//down load this theme

}
        });  
    }  

private List<String> mThemesNames = null;
private List<Bitmap> mThemesBitmaps = null;
    private class ImageAdapter extends BaseAdapter{  
        private Context mContext;  
  
        public ImageAdapter(Context context) {  
            this.mContext=context;  
        }  
  
        @Override  
        public int getCount() {  
            return mThemesNames.size()+1;  
        }  

   @Override  
        public Object getItem(int position) {
if(position == mThemesNames.size()) 
return BitmapFactory. decodeResource (ThemePickerActivity.this.getResources(), R.drawable.default_scene);
else 
            return mThemesBitmaps.get(position);  
        }  
  
        @Override  
        public long getItemId(int position) {  
            return 0;  
        }  

        @Override  
        public View getView(int position, View convertView, ViewGroup parent) {  
            ImageView imageView;  
            if(convertView==null){  
                imageView=new ImageView(mContext);  
                imageView.setLayoutParams(new GridView.LayoutParams(280, 478));  
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);  
                imageView.setPadding(8, 8, 8, 8);  
            }else{  
                imageView = (ImageView) convertView;  
            }
if(position == mThemesNames.size())  
imageView.setImageBitmap(BitmapFactory. decodeResource (ThemePickerActivity.this.getResources(), R.drawable.default_scene));
else  
            imageView.setImageBitmap(mThemesBitmaps.get(position));  
            return imageView;  
        }  
          
  
          
    }

  private void getThemeBitmaps(String path){
mThemesNames = new ArrayList<String>();
mThemesBitmaps = new ArrayList<Bitmap>();
List<String> themetitles = new ArrayList<String>();
File pathFile = new File(path);
if(pathFile.exists() && pathFile.isDirectory()){
  String[] fileNames = pathFile.list();
if(fileNames.length <= 0)
return;
for(String filename:fileNames){
   File subFile = new File(path+"/"+filename);
if(subFile.exists() && (!subFile.isDirectory()) && subFile.getName().endsWith(".png")){
Bitmap bitmap = android.graphics.BitmapFactory.decodeFile(path+"/"+filename);
String namekey = trimExtension(filename);
if(bitmap !=null && (namekey != null) ){
mThemesNames.add(namekey);
mThemesBitmaps.add(bitmap);
}
}
}
}
}

private String trimExtension(String filename) 
{          
if ((filename != null) && (filename.length() > 0)) {              
int i = filename.lastIndexOf('.');              
 if ((i >-1) && (i < (filename.length()))) {                  
 return filename.substring(0, i);              
 }          
 }          
  return null;      
  }
  
  private boolean isFileEffect(String name){
  File file = new File(name);
  if(file.exists() && file.isDirectory() && (file.list().length > 0) )
      return true;
  else 
      return false;
  
  }
}

3 /packages/apps/Launcher3/src/com/android/launcher3/Hotseat.java

    public Hotseat(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);


        Resources r = context.getResources();
/*
Drawable d = null;
String themeKeyname = context.getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
                Context.MODE_PRIVATE).getString("theme_key","default");
if (!themeKeyname.equals("default")) {
String workbgpath = "mnt/sdcard/theme/" + themeKeyname +"/"
  + themeKeyname + "_workspace_bg.png";
if(new File(workbgpath).exists()){
d = new android.graphics.drawable.BitmapDrawable( BitmapFactory.decodeFile(workbgpath) );
}
}
if(d!=null)
setBackgroundDrawable(d);
*/

 mTransposeLayoutWithOrientation = 
                r.getBoolean(R.bool.hotseat_transpose_layout_with_orientation);
        mIsLandscape = context.getResources().getConfiguration().orientation ==
            Configuration.ORIENTATION_LANDSCAPE;
    }


 void resetLayout() {
        mContent.removeAllViewsInLayout();


        if (!AppsCustomizePagedView.DISABLE_ALL_APPS) {
            // Add the Apps button
            Context context = getContext();


            LayoutInflater inflater = LayoutInflater.from(context);
            TextView allAppsButton = (TextView)
                    inflater.inflate(R.layout.all_apps_button, mContent, false);
//add by xuxin
Drawable d;
String themeKeyname = context.getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
                Context.MODE_PRIVATE).getString("theme_key","default");
//android.os.SystemProperties.get("persist.sys.theme.key", "default");

if (!themeKeyname.equals("default")) {
 String iconpath = "mnt/sdcard/theme/" + themeKeyname +"/"
  + themeKeyname + "_all_apps.png";
 if(new File(iconpath).exists()){
d = new FastBitmapDrawable(BitmapFactory.decodeFile(iconpath));
 }else{
              d = context.getResources().getDrawable(R.drawable.all_apps_button_icon);
 }
           
      }else{
// add by xuxin
             d = context.getResources().getDrawable(R.drawable.all_apps_button_icon);
}

 Utilities.resizeIconDrawable(d);
            allAppsButton.setCompoundDrawables(null, d, null, null);


            allAppsButton.setContentDescription(context.getString(R.string.all_apps_button_label));
            if (mLauncher != null) {
                allAppsButton.setOnTouchListener(mLauncher.getHapticFeedbackTouchListener());
            }
            allAppsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(android.view.View v) {
                    Trace.traceBegin(Trace.TRACE_TAG_INPUT, "onClick");
                    if (LauncherLog.DEBUG) {
                        LauncherLog.d(TAG, "Click on all apps view on hotseat: mLauncher = " + mLauncher);
                    }
                    if (mLauncher != null) {
                        mLauncher.onClickAllAppsButton(v);
                    }
                    Trace.traceEnd(Trace.TRACE_TAG_INPUT);
                }
            });

 // Note: We do this to ensure that the hotseat is always laid out in the orientation of
            // the hotseat in order regardless of which orientation they were added
            int x = getCellXFromOrder(mAllAppsButtonRank);
            int y = getCellYFromOrder(mAllAppsButtonRank);
            CellLayout.LayoutParams lp = new CellLayout.LayoutParams(x,y,1,1);
            lp.canReorder = false;
            mContent.addViewToCellLayout(allAppsButton, -1, 0, lp, true);
        }
    }


4 packages\apps\Launcher3\src\com\android\launcher3\IconCache.java

     mSharedPrefs = context.getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
                Context.MODE_PRIVATE);

    public Drawable getFullResIcon(Resources resources, int iconId) {
        Drawable d;
        try {
d = resources.getDrawableForDensity(iconId, mIconDpi);
Bitmap b = addThemeLogo(((BitmapDrawable)d).getBitmap());


d = new FastBitmapDrawable (b);
        } catch (Resources.NotFoundException e) {
            d = null;
        }


        return (d != null) ? d : getFullResDefaultActivityIcon();
    }

    public Drawable getFullResIcon(String packageName, int iconId) {
//add by xuxin
String themeKeyname = mSharedPrefs.getString("theme_key","default");
//android.os.SystemProperties.get("persist.sys.theme.key", "default");
if (!themeKeyname.equals("default")) {
 String iconpath = "mnt/sdcard/theme/" + themeKeyname +"/"
  + themeKeyname + "_" + convertToIconResName(packageName)+".png";
 if(new File(iconpath).exists()){
return new FastBitmapDrawable(BitmapFactory.decodeFile(iconpath));
 }
           
      }
// add by xuxin

}

    public Drawable getFullResIcon(ActivityInfo info) {
//add by xuxin
String themeKeyname = mSharedPrefs.getString("theme_key","default");//android.os.SystemProperties.get("persist.sys.theme.key", "default");
String iconpath;
if (!themeKeyname.equals("default")) {
iconpath = "mnt/sdcard/theme/" + themeKeyname +"/"
  + themeKeyname + "_" + convertToIconResName(info.name)+".png";
       if(new File(iconpath).exists()){
return new FastBitmapDrawable(BitmapFactory.decodeFile(iconpath));
}else{
iconpath = "mnt/sdcard/theme/" + themeKeyname +"/"
  + themeKeyname + "_" + convertToIconResName(info.packageName)+".png";
if(new File(iconpath).exists()){
return new FastBitmapDrawable(BitmapFactory.decodeFile(iconpath));
}
}
       }
//add by xuxin

}

    private CacheEntry cacheLocked(ComponentName componentName, ResolveInfo info,
            HashMap<Object, CharSequence> labelCache) {

//add by xuxin
String themeKeyname = mSharedPrefs.getString("theme_key","default");//android.os.SystemProperties.get("persist.sys.theme.key", "default");
System.out.println("get key --- " + themeKeyname);
String iconpath;
if (!themeKeyname.equals("default")) {
iconpath = "mnt/sdcard/theme/" + themeKeyname +"/"
  + themeKeyname + "_" + convertToIconResName(info.activityInfo.name)+".png";
if(new File(iconpath).exists()){
entry.icon = BitmapFactory.decodeFile(iconpath);
}else{
iconpath = "mnt/sdcard/theme/" + themeKeyname +"/"
  + themeKeyname + "_" + convertToIconResName(info.activityInfo.packageName)+".png";
if(new File(iconpath).exists()){
entry.icon = BitmapFactory.decodeFile(iconpath);
}else{
entry.icon = Utilities.createIconBitmap(
                   getFullResIcon(info), mContext);
}
}
}else{
entry.icon = Utilities.createIconBitmap(
                   getFullResIcon(info), mContext);
}
//add by xuxin

}

private String convertToIconResName(String input) {
       return input != null && !input.equals("") ? input.replace('.', '_').toLowerCase() : input;
    }

private Bitmap addThemeLogo(Bitmap srcBitmap){
String themeKeyname = mSharedPrefs.getString("theme_key","default");//android.os.SystemProperties.get("persist.sys.theme.key", "default");
  
Bitmap b2 = BitmapFactory.decodeFile("mnt/sdcard/theme/"+themeKeyname +"/"+themeKeyname+"_icon_bg.png");
    if (themeKeyname.equals("default") || b2 == null) {
  return srcBitmap;
  }
Bitmap b3 = Bitmap.createBitmap(srcBitmap.getWidth()+5, srcBitmap.getHeight()+5, srcBitmap.getConfig());
Canvas canvas = new Canvas(b3);
canvas.drawBitmap(srcBitmap,0,0,new Paint(Paint.FILTER_BITMAP_FLAG));
canvas.drawBitmap(b2,0,Math.abs(srcBitmap.getHeight()-b2.getHeight()),new Paint(Paint.FILTER_BITMAP_FLAG));
return b3;   
    }


5 packages/apps/Launcher3/AndroidManifest.xml

   <activity
            android:name="com.android.launcher3.ThemePickerActivity"
            android:icon="@drawable/theme_icon"
               android:launchMode="singleTask"
            android:clearTaskOnLaunch="true">
<intent-filter>
                   <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
        </activity>

你可能感兴趣的:(在Launcher3中增加主题切换功能)