您的位置:首页 > 移动开发 > Android开发

Android平常用到的小工具

2012-03-14 17:37 399 查看
问题
解决方案:
EditText 设置背景为空
Android:backGround = "@null"
全屏显示
注:要在setContentView()前使用

requestWindowFeature(Window.FEATURE_NO_TITLE); //隐藏标题 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //设置全屏
开启程序横屏显示
方法一:在Androidmanifest里设置如下:

android:screenOrientation="landscape"

方法二:setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
\\fileserver\Share\Public
setTheme(android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
实现图片平铺效果
<?xml version ="1.0" encoding ="utf-8" ?>

<bitmap xmlns:android ="http://schemas.android.com/apk/res/android"

android:src ="@drawable/pattern"

android:tileMode ="repeat" />
将键盘上的回车键改为搜索键
android:imeOptions="actionSearch"
ListView 设置字体颜色
android:cacheColorHint="#00FF0000" 设置阴影色
Sharepreferences
存储类型 (boolean、int、float、long和String) 键值对方式
listView.setCacheColorHint(0);
GridView设置点击效果透明
personal_gridview.setSelector(R.drawable.transparent);
背景色平铺
<?xml version ="1.0" encoding ="utf-8" ?>

<bitmap

xmlns:android ="http://schemas.android.com/apk/res/android"

android:src ="@drawable/more_bg"

android:tileMode ="repeat" />
分享微博 系统自带
Intent intent=new Intent(Intent.ACTION_SEND);

intent.setType("text/plain"); //分享的数据类型

intent.putExtra(Intent.EXTRA_SUBJECT, "打电话"); //主题

intent.putExtra(Intent.EXTRA_TEXT, "android拨打电话"); // 内容

startActivity(Intent.createChooser(intent, "拨打电话")); //目标应 用选择对话框的标题
在mainFinest里面设置activity风格
android:theme="@android:style/Theme.Dialog"
android popupwindow
设置按钮与图片位置
android:drawableLeft="@drawable/friend_dot"
使程序高清
<supports-screens android:largeScreens="true"

android:normalScreens="true" android:smallScreens="true"

android:anyDensity="true" />
获取相册uri并转为 绝对路径
Uri uri = data.getData();

ContentResolver cr = this.getContentResolver();

Cursor cursor = cr.query(uri, null, null, null, null);

cursor.moveToFirst();

for (int i = 0; i < cursor.getColumnCount(); i++) {

Log.i("URI", i + "-----------------" + cursor.getString(i));

}

String ImagePath = cursor.getString(cursor.getColumnIndex("_data"));
关于相册
String status=Environment.getExternalStorageState();

status.equals(Environment.MEDIA_MOUNTED)//判断是否有sd卡

Intent i =

new Intent("android.media.action.IMAGE_CAPTURE");//调用系统照相功能

startActivityForResult(i, TAKEPHOTO);

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); //从相册中取

intent.addCategory(Intent.CATEGORY_OPENABLE);

intent.setType("image/*");

instance.startActivityForResult(Intent.createChooser(

intent, "选择图片"), TAKEPICTURE);
UUID+设备号序列号 唯一识别码(不可变)
private String getMyUUID(){

final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

final String tmDevice, tmSerial, tmPhone, androidId;

tmDevice = "" + tm.getDeviceId();

tmSerial = "" + tm.getSimSerialNumber();

androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);

UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());

String uniqueId = deviceUuid.toString();

Log.d("debug","uuid="+uniqueId);

return uniqueId;

}
java 获取可变UUID
private String getMyUUID(){

UUID uuid = UUID.randomUUID();

String uniqueId = uuid.toString();

Log.d("debug","----->UUID"+uuid);

return uniqueId;

}
获取sim卡信息
getLine1Number():获取到手机号码; getDeviceSoftwareVersion:获取到Android操作系统的版本; getSimSerialNumber:获取到SIM卡唯一编号ID; getSubscriberId:获取到客户ID,即IMSI;
获取Gmail方法
private String getGmail() {

String userName = null;

Cursor userCursor = getContentResolver().query(Uri.parse(URL), null,

null, null, null);

if (userCursor.getCount() > 0) {

userCursor.moveToFirst();

userName = userCursor.getString(userCursor.getColumnIndex("name"));

Log.i("QQ", userName);

}

if (userName.equals("mycalendar")) {

userName = "";

}

return userName;

}
Spinner 设置默认选项
spinner1.setSelection(1);
在activity清单中
android:windowSoftInputMode="adjustPan" 是配置界面不被键盘挤上去的 android:windowSoftInputMode="stateAlwaysHidden" 不弹出键盘
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
将editText 输入完后键盘确定键变为搜索
search_edit.setOnEditorActionListener(new OnEditorActionListener() {//

@Override

public boolean onEditorAction(TextView v, int actionId,

KeyEvent event) {

Toast.makeText(instance,"搜索",Toast.LENGTH_SHORT).show();

InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

mInputMethodManager.hideSoftInputFromWindow(v.getWindowToken(),

0);

return false;

}

}); android:imeOptions="actionSearch"
RelativeLayout 属性
    熟练掌握以下重要属性,并灵活运用:

    android:layout_centerInParent   居中布局

    android:layout_centerVertical    水平居中布局

    android:layout_centerHorizontal  垂直居中布局

    android:layout_alignParentTop    居于容器内顶部

    android:layout_alignParentBottom  居于容器内底部

    android:layout_alignParentLeft    居于容器内左边

    android:layout_alignParentRight    居于容器内右边

    android:layout_above       居于指定View的上方

    android:layout_below       居于指定View的下方

    android:layout_toRightOf      在指定View的右边

    android:layout_toLeftOf       在指定View的左边

    android:layout_alignTop      与指定View的Top一致
Intent传递参数
第一个activity Intent intent = new Intent(); intent.putExtra("key","value"); intent.setClass(a.this,b.class); startActivity(intent); 第二个Activity Intent intent = getIntent(); intent.getStringExtra("key");
古宁给的,判断系统是否有发邮件的包
public boolean checkApkExist(Context context, String packageName) {

if (packageName == null || "".equals(packageName))

return false;

try {

ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,

PackageManager.GET_UNINSTALLED_PACKAGES);

if (info != null) {

return true;

}

return false;

} catch (NameNotFoundException e) {

return false;

}

}
防止EditText自动获得焦点
方法一:android:focusableInTouchMode="true"方法二: 或者在oncreate中加入下列代码getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);//防止editText自动获得家电
获取屏幕宽度和高度
//取得窗口属性

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

//获得当前屏幕的高

screen_height = displayMetrics.heightPixels;

//获得当前屏幕的宽

screen_width = displayMetrics.widthPixels;
intent传递bitmap
Intent intent = getIntent();

Bitmap myBitmap = (Bitmap) intent.getParcelableExtra("tupian");

imageView.setImageBitmap(myBitmap); Intent的使用,在intent中有一种方法getSerializableExtra()用来接收一系列的数据,比如ArrayList里的数据
NumberFormatException 数字格式遗产
闹铃管理器
AlarmManager
更新listView
notifyDataSetChanged notifyDataSetChanged()可以在修改适配器绑定的数组后,不用重新刷新Activity,通知Activity更新ListView
判断是否有sd卡
if(status.equals(Environment.MEDIA_MOUNTED)){

Toast.makeText(instance, "有SD卡", Toast.LENGTH_SHORT).show();

}

else{

Toast.makeText(instance, "没有SD卡", Toast.LENGTH_SHORT).show();

}
将图片写到sd卡的根目录下
String sdcard = android.os.Environment

.getExternalStorageDirectory().toString();

FileOutputStream fos = new FileOutputStream(sdcard

+ "/item" + gallery.getSelectedItemPosition() + ".jpg");

((BitmapDrawable) getResources().getDrawable(

imageResIdList.get(gallery

.getSelectedItemPosition()))).getBitmap()

.compress(CompressFormat.JPEG, 50, fos);

fos.close();
获得SD卡路径
String sdDir = Environment.getExternalStorageDirectory().toString();//获取跟目录

用ViewFlipper 设置进入进出动画
ageFlipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.push_up_in));

ageFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.push_up_out));
调用系统工具播放录音
//调用系统工具播放录音

private void startReco(){

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.fromFile(new File(recPath)), "audio/mp3");

startActivity(intent);

// Intent i = new Intent();

// i.setClass(PartMultimediaActivity.this, PlayVideo.class);

// i.putExtra("videoPath", videoPath);

// startActivityForResult(i, 111);

}
取得listView里EditText的值
(EditText)context.listView.getChildAt(0).findViewById(R.id.a).getText().toString();
从sd卡中取得的图片的路径
Uri dataUri = data.getData();

ContentResolver cr = this.getContentResolver();

Cursor cursor = cr.query(dataUri, null, null, null, null);

cursor.moveToFirst();

userImagePath = cursor.getString(1);

Log.d("debug", "从相册中获得的图片路径"+userImagePath);
从相册,内存卡等取得图片的方法
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

intent.addCategory(Intent.CATEGORY_OPENABLE);

intent.setType("image/*");

AlertActivity.this.startActivityForResult(Intent.createChooser(

intent, "选择图片"), TAKEPICTURE);
将图片变成圆角
BitmapFactory.Options options = new BitmapFactory.Options();

options.inSampleSize = 4;

userBitmap = BitmapFactory.decodeFile(userImagePath, options);
将图片设置成圆角
/**

* 图片圆角

*

* @param bitmap

* @return

*/

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 = 12;

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;

}
设置listView 的headView 不可点击
listView.addHeaderView(headView,null,false)
设置editText 不弹出软键盘
editView.setInputType(InputType.TYPE_NULL)
文字超出长度则截断
int MAX_LENGTH = 140; if(status.getStatus()!= null && status.getStatus().length() > StatusSetRequestParam.MAX_LENGTH) {

status = status.trim();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android工具
相关文章推荐