六十一、Android创建桌面快捷方式:
- /**
- * 为程序创建桌面快捷方式
- */
- private void addShortcut(){
- Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
- //快捷方式的名称
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
- shortcut.putExtra("duplicate", false); //不允许重复创建
- //指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
- //注意: ComponentName的第二个参数必须加上点号(.),否则快捷方式无法启动相应程序
- ComponentName comp = new ComponentName(this.getPackageName(),"."+this.getLocalClassName());
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, newIntent(Intent.ACTION_MAIN).setComponent(comp));
- //快捷方式的图标
- ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
- sendBroadcast(shortcut);
- }
需要声明权限:
- <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
http://www.cnblogs.com/-OYK/archive/2011/05/31/2064797.html
http://www.apkbus.com/android-17389-1-1.html
http://dev.10086.cn/cmdn/wiki/index.php?edition-view-8836-1.html
六十二、android画图去锯齿效果
paint.setAntiAlias(true);
画图片的时候,前面设置没有用
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
六十三、获取sd卡里文件信息
- public class SDFileExplorer extends Activity{
- ListView listView;
- TextView textView;
- // 记录当前的父文件夹
- File currentParent;
- // 记录当前路径下的所有文件的文件数组
- File[] currentFiles;
- @Override
- public void onCreate(Bundle savedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //获取列出全部文件的ListView
- listView = (ListView) findViewById(R.id.list);
- textView = (TextView) findViewById(R.id.path);
- //获取系统的SD卡的目录
- File root = new File("/mnt/sdcard/");
- //如果 SD卡存在
- if (root.exists()){
- currentParent = root;
- currentFiles = root.listFiles();
- //使用当前目录下的全部文件、文件夹来填充ListView
- inflateListView(currentFiles);
- }
- // 为ListView的列表项的单击事件绑定监听器
- listView.setOnItemClickListener(new OnItemClickListener(){
- @Override
- public void onItemClick(AdapterView<?> parent, View view,
- int position, long id){
- // 用户单击了文件,直接返回,不做任何处理
- if (currentFiles[position].isFile())
- return;
- // 获取用户点击的文件夹下的所有文件
- File[] tmp = currentFiles[position].listFiles();
- if (tmp == null || tmp.length == 0){
- Toast.makeText(SDFileExplorer.this, "当前路径不可访问或该路径下没有文件",
- 20000).show();
- }else{
- //获取用户单击的列表项对应的文件夹,设为当前的父文件夹
- currentParent = currentFiles[position];
- //保存当前的父文件夹内的全部文件和文件夹
- currentFiles = tmp;
- // 再次更新ListView
- inflateListView(currentFiles);
- }
- }
- });
- // 获取上一级目录的按钮
- Button parent = (Button) findViewById(R.id.parent);
- parent.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View source){
- try{
- if (!currentParent.getCanonicalPath().equals("/mnt/sdcard")){
- // 获取上一级目录
- currentParent = currentParent.getParentFile();
- // 列出当前目录下所有文件
- currentFiles = currentParent.listFiles();
- // 再次更新ListView
- inflateListView(currentFiles);
- }
- }
- catch (IOException e){
- e.printStackTrace();
- }
- }
- });
- }
- private void inflateListView(File[] files){
- // 创建一个List集合,List集合的元素是Map
- List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
- for (int i = 0; i < files.length; i++){
- Map<String, Object> listItem = new HashMap<String, Object>();
- //如果当前File是文件夹,使用folder图标;否则使用file图标
- if (files[i].isDirectory()){
- listItem.put("icon", R.drawable.folder);
- }else{
- listItem.put("icon", R.drawable.file);
- }
- listItem.put("fileName", files[i].getName());
- //添加List项
- listItems.add(listItem);
- }
- // 创建一个SimpleAdapter
- SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
- R.layout.line, new String[] { "icon", "fileName" }, new int[] {
- R.id.icon, R.id.file_name });
- // 为ListView设置Adapter
- listView.setAdapter(simpleAdapter);
- try{
- textView.setText("当前路径为:" + currentParent.getCanonicalPath());
- }catch (IOException e){
- e.printStackTrace();
- }
- }
- }
六十四、Android标题栏显示progressBar
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先给Activity注册界面进度条功能
- setContentView(R.layout.main);
- setProgressBarIndeterminateVisibility(true);//在需要显示进度条的时候调用这个方法
- setProgressBarIndeterminateVisibility(false);//在不需要显示进度条的时候调用这个方法
- }
六十五、单击EditText全选内容
- percent.setOnTouchListener(this);
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- if(v.getId()==R.id.seekPercent) {
- percent.selectAll();
- InputMethodManager imm = (InputMethodManager)
- context.getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.showSoftInput(v, 0);
- return true;
- }
- return false;
- }
六十六、Android设置图片圆角
- /**
- * 将图片设置为圆角
- */
- public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
- Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
- bitmap.getHeight(), Config.ARGB_8888);
- Canvas canvas = new Canvas(output);
- final int color = 0xff424242;
- final Paint paint = new Paint();
- final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
- final RectF rectF = new RectF(rect);
- final float roundPx = pixels;
- paint.setAntiAlias(true);
- canvas.drawARGB(0, 0, 0, 0);
- paint.setColor(color);
- canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
- paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
- canvas.drawBitmap(bitmap, rect, rect, paint);
- return output;
- }
六十七、把图片转换成圆形
- bitmap = ((BitmapDrawable)imageView1.getDrawable()).getBitmap();
- bitmap = getRoundedCornerBitmap(bitmap);
- imageView1.setImageBitmap(bitmap);
- public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
- Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
- bitmap.getHeight(), Config.ARGB_8888);
- Canvas canvas = new Canvas(output);
- final int color = 0xff424242;
- final Paint paint = new Paint();
- final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
- final RectF rectF = new RectF(rect);
- final float roundPx = bitmap.getWidth() / 2;
- paint.setAntiAlias(true);
- canvas.drawARGB(0, 0, 0, 0);
- paint.setColor(color);
- canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
- paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
- canvas.drawBitmap(bitmap, rect, rect, paint);
- return output;
- }
六十八、TextView高级应用
1. 自定义字体
可以使用setTypeface(Typeface)方法来设置文本框内文本的字体,而android的 Typeface又使用TTF字体文件来设置字体
所以,我们可以在程序中放入TTF字体文件,在程序中使用Typeface来设置字体:第一步,在assets目录下新建fonts目录,把TTF字体文件放到这里。第二步,程序中调用:
TextViewtv = (TextView)findViewById(R.id.textView);
AssetManagermgr=getAssets();//得到AssetManager
Typefacetf=Typeface.createFromAsset(mgr, "fonts/mini.TTF");//根据路径得到Typeface
tv.setTypeface(tf);//设置字体
效果如下图所示:
2. 显示多种颜色的字
Android支持html格式的字符串,通过调用Html.fromHtml(str)方法可以转换html格式的字符串str。
示例如下:
StringtextStr1 = "<font color=\"#ffff00\">如果有一天,</font><br>";
StringtextStr2 = "<font color=\"#00ff00\">我厌倦了这里,</font><br>";
StringtextStr3 = "<font color=\"#ff00ff\">我会乘着梦,</font><br>";
StringtextStr4 = "<font color=\"#00ffff\">飞向那个属于自己的<br>世界……</font><br>";
tv.setText(Html.fromHtml(textStr1+textStr2+textStr3+textStr4));
运行后效果如下:
3. 字体加粗
在xml布局文件中使用android:textStyle=”bold”可以将英文设置成粗体,但是不能将中文设置成粗体,将中文设置成粗体的方法是:使用TextPaint的仿“粗体”设置setFakeBoldText为true。示例代码如下:
tv.getPaint().setFakeBoldText(true);
效果如下:
4. 添加阴影
在xml布局文件中使用一系列android:shadowXXX属性可添加设置阴影。具体为:shadowColor设置阴影颜色;shadowDx设置阴影水平偏移量;shadowDy设置阴影垂直偏移量;shadowRadius设置阴影半径。
示例代码:
android:shadowColor="#ffffff"
android:shadowDx="15.0"
android:shadowDy="5.0"
android:shadowRadius="2.5"
显示效果如下:
5. 插入图片
插入图片有两种方法,第一种方法就是用上面说的html格式的字符串,不过转换稍微有些麻烦。需要用到ImageGetter类来对图片的src属性进行转换。示例代码如下:
StringimgStr = "<img src=\""+R.drawable.sidai+"\"/>";
Html.ImageGetterimageGetter = new Html.ImageGetter() {
public Drawable getDrawable(Stringarg0) {
// TODO Auto-generated methodstub
int id =Integer.parseInt(arg0);
Drawable draw =getResources().getDrawable(id);
draw.setBounds(10, 10, 228,300);
return draw;
}
};
tv.append(Html.fromHtml(imgStr,imageGetter,null));
第二种方法是使用xml布局文件中一系列android:drawableXXX属性来实现插入图片。具体为:drawableBottom是在文本框内文本的底端绘制指定图像;drawableLeft是在文本框内文本的左边绘制指定图像;drawableRight是在文本框内文本的右边绘制指定图像;drawableTop是在文本框内文本的顶端绘制指定图像;drawablePadding设置文本框内文本与图像之间的间距。示例代码:
android:drawableBottom=”@drawable/sidai”
六十九、资源plurals表示数量的各种方式,比如:一个教室有多少学生。考虑下面的例子:
there is 1 student;
there are 2 students;
there are 50 students;
显然对于2,50句子格式是一样的,对于1不同,Android支持将这种变体表示为plurals资源。
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="hello">Hello World, Resource_Plurals!</string>
- <string name="app_name">Resource_Plurals</string>
- <plurals name="student">
- <item quantity="one">There is 1 student</item>
- <item quantity="other">There are %d students</item>
- </plurals>
- </resources>
- public class Resource_Plurals extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Resources r = getResources();
- String s1 = r.getQuantityString(R.plurals.student, 1,1);
- Log.i("plurals", s1);
- String s2 = r.getQuantityString(R.plurals.student, 2,2);
- Log.i("plurals", s2);
- String s3 = r.getQuantityString(R.plurals.student, 50,50);
- Log.i("plurals", s3);
- }
- }
七十、Android 自定义json解析类
- import java.lang.reflect.Method;
- import java.util.Collection;
- import java.util.Map;
- import java.util.Set;
- public final class JsonUtil{
- /**
- * 把对象封装为JSON格式
- *
- * @param o
- * 对象
- * @return JSON格式
- */
- @SuppressWarnings("unchecked")
- public static String toJson(final Object o){
- if (o == null){
- return "null";
- }
- if (o instanceof String) //String{
- return string2Json((String) o);
- }
- if (o instanceof Boolean) //Boolean{
- return boolean2Json((Boolean) o);
- }
- if (o instanceof Number) //Number{
- return number2Json((Number) o);
- }
- if (o instanceof Map) //Map{
- return map2Json((Map<String, Object>) o);
- }
- if (o instanceof Collection) //List Set{
- return collection2Json((Collection) o);
- }
- if (o instanceof Object[]) //对象数组{
- return array2Json((Object[]) o);
- }
- if (o instanceof int[])//基本类型数组
- {
- return intArray2Json((int[]) o);
- }
- if (o instanceof boolean[])//基本类型数组
- {
- return booleanArray2Json((boolean[]) o);
- }
- if (o instanceof long[])//基本类型数组
- {
- return longArray2Json((long[]) o);
- }
- if (o instanceof float[])//基本类型数组
- {
- return floatArray2Json((float[]) o);
- }
- if (o instanceof double[])//基本类型数组
- {
- return doubleArray2Json((double[]) o);
- }
- if (o instanceof short[])//基本类型数组
- {
- return shortArray2Json((short[]) o);
- }
- if (o instanceof byte[])//基本类型数组
- {
- return byteArray2Json((byte[]) o);
- }
- if (o instanceof Object) //保底收尾对象
- {
- return object2Json(o);
- }
- throw new RuntimeException("不支持的类型: " + o.getClass().getName());
- }
- /**
- * 将 String 对象编码为 JSON格式,只需处理好特殊字符
- *
- * @param s
- * String 对象
- * @return JSON格式
- */
- static String string2Json(final String s)
- {
- final StringBuilder sb = new StringBuilder(s.length() + 20);
- sb.append('\"');
- for (int i = 0; i < s.length(); i++)
- {
- final char c = s.charAt(i);
- switch (c)
- {
- case '\"':
- sb.append("\\\"");
- break;
- case '\\':
- sb.append("\\\\");
- break;
- case '/':
- sb.append("\\/");
- break;
- case '\b':
- sb.append("\\b");
- break;
- case '\f':
- sb.append("\\f");
- break;
- case '\n':
- sb.append("\\n");
- break;
- case '\r':
- sb.append("\\r");
- break;
- case '\t':
- sb.append("\\t");
- break;
- default:
- sb.append(c);
- }
- }
- sb.append('\"');
- return sb.toString();
- }
- /**
- * 将 Number 表示为 JSON格式
- *
- * @param number
- * Number
- * @return JSON格式
- */
- static String number2Json(final Number number)
- {
- return number.toString();
- }
- /**
- * 将 Boolean 表示为 JSON格式
- *
- * @param bool
- * Boolean
- * @return JSON格式
- */
- static String boolean2Json(final Boolean bool)
- {
- return bool.toString();
- }
- /**
- * 将 Collection 编码为 JSON 格式 (List,Set)
- *
- * @param c
- * @return
- */
- static String collection2Json(final Collection<Object> c)
- {
- final Object[] arrObj = c.toArray();
- return toJson(arrObj);
- }
- /**
- * 将 Map<String, Object> 编码为 JSON 格式
- *
- * @param map
- * @return
- */
- static String map2Json(final Map<String, Object> map)
- {
- if (map.isEmpty())
- {
- return "{}";
- }
- final StringBuilder sb = new StringBuilder(map.size() << 4); //4次方
- sb.append('{');
- final Set<String> keys = map.keySet();
- for (final String key : keys)
- {
- final Object value = map.get(key);
- sb.append('\"');
- sb.append(key); //不能包含特殊字符
- sb.append('\"');
- sb.append(':');
- sb.append(toJson(value)); //循环引用的对象会引发无限递归
- sb.append(',');
- }
- // 将最后的 ',' 变为 '}':
- sb.setCharAt(sb.length() - 1, '}');
- return sb.toString();
- }
- /**
- * 将数组编码为 JSON 格式
- *
- * @param array
- * 数组
- * @return JSON 格式
- */
- static String array2Json(final Object[] array)
- {
- if (array.length == 0)
- {
- return "[]";
- }
- final StringBuilder sb = new StringBuilder(array.length << 4); //4次方
- sb.append('[');
- for (final Object o : array)
- {
- sb.append(toJson(o));
- sb.append(',');
- }
- // 将最后添加的 ',' 变为 ']':
- sb.setCharAt(sb.length() - 1, ']');
- return sb.toString();
- }
- static String intArray2Json(final int[] array)
- {
- if (array.length == 0)
- {
- return "[]";
- }
- final StringBuilder sb = new StringBuilder(array.length << 4);
- sb.append('[');
- for (final int o : array)
- {
- sb.append(Integer.toString(o));
- sb.append(',');
- }
- // set last ',' to ']':
- sb.setCharAt(sb.length() - 1, ']');
- return sb.toString();
- }
- static String longArray2Json(final long[] array)
- {
- if (array.length == 0)
- {
- return "[]";
- }
- final StringBuilder sb = new StringBuilder(array.length << 4);
- sb.append('[');
- for (final long o : array)
- {
- sb.append(Long.toString(o));
- sb.append(',');
- }
- // set last ',' to ']':
- sb.setCharAt(sb.length() - 1, ']');
- return sb.toString();
- }
- static String booleanArray2Json(final boolean[] array)
- {
- if (array.length == 0)
- {
- return "[]";
- }
- final StringBuilder sb = new StringBuilder(array.length << 4);
- sb.append('[');
- for (final boolean o : array)
- {
- sb.append(Boolean.toString(o));
- sb.append(',');
- }
- // set last ',' to ']':
- sb.setCharAt(sb.length() - 1, ']');
- return sb.toString();
- }
- static String floatArray2Json(final float[] array)
- {
- if (array.length == 0)
- {
- return "[]";
- }
- final StringBuilder sb = new StringBuilder(array.length << 4);
- sb.append('[');
- for (final float o : array)
- {
- sb.append(Float.toString(o));
- sb.append(',');
- }
- // set last ',' to ']':
- sb.setCharAt(sb.length() - 1, ']');
- return sb.toString();
- }
- static String doubleArray2Json(final double[] array)
- {
- if (array.length == 0)
- {
- return "[]";
- }
- final StringBuilder sb = new StringBuilder(array.length << 4);
- sb.append('[');
- for (final double o : array)
- {
- sb.append(Double.toString(o));
- sb.append(',');
- }
- // set last ',' to ']':
- sb.setCharAt(sb.length() - 1, ']');
- return sb.toString();
- }
- static String shortArray2Json(final short[] array)
- {
- if (array.length == 0)
- {
- return "[]";
- }
- final StringBuilder sb = new StringBuilder(array.length << 4);
- sb.append('[');
- for (final short o : array)
- {
- sb.append(Short.toString(o));
- sb.append(',');
- }
- // set last ',' to ']':
- sb.setCharAt(sb.length() - 1, ']');
- return sb.toString();
- }
- static String byteArray2Json(final byte[] array)
- {
- if (array.length == 0)
- {
- return "[]";
- }
- final StringBuilder sb = new StringBuilder(array.length << 4);
- sb.append('[');
- for (final byte o : array)
- {
- sb.append(Byte.toString(o));
- sb.append(',');
- }
- // set last ',' to ']':
- sb.setCharAt(sb.length() - 1, ']');
- return sb.toString();
- }
- public static String object2Json(final Object bean)
- {
- //数据检查
- if (bean == null)
- {
- return "{}";
- }
- final Method[] methods = bean.getClass().getMethods(); //方法数组
- final StringBuilder sb = new StringBuilder(methods.length << 4); //4次方
- sb.append('{');
- for (final Method method : methods)
- {
- try
- {
- final String name = method.getName();
- String key = "";
- if (name.startsWith("get"))
- {
- key = name.substring(3);
- //防死循环
- final String[] arrs =
- { "Class" };
- boolean bl = false;
- for (final String s : arrs)
- {
- if (s.equals(key))
- {
- bl = true;
- continue;
- }
- }
- if (bl)
- {
- continue; //防死循环
- }
- }
- else if (name.startsWith("is"))
- {
- key = name.substring(2);
- }
- if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0)
- {
- if (key.length() == 1)
- {
- key = key.toLowerCase();
- }
- else if (!Character.isUpperCase(key.charAt(1)))
- {
- key = key.substring(0, 1).toLowerCase() + key.substring(1);
- }
- final Object elementObj = method.invoke(bean);
- //System.out.println("###" + key + ":" + elementObj.toString());
- sb.append('\"');
- sb.append(key); //不能包含特殊字符
- sb.append('\"');
- sb.append(':');
- sb.append(toJson(elementObj)); //循环引用的对象会引发无限递归
- sb.append(',');
- }
- }
- catch (final Exception e)
- {
- //e.getMessage();
- throw new RuntimeException("在将bean封装成JSON格式时异常:" + e.getMessage(), e);
- }
- }
- if (sb.length() == 1)
- {
- return bean.toString();
- }
- else
- {
- sb.setCharAt(sb.length() - 1, '}');
- return sb.toString();}
- }
- private JsonUtil(){
- }
- }