安卓开发一些基础的设置代码_第1页
安卓开发一些基础的设置代码_第2页
安卓开发一些基础的设置代码_第3页
安卓开发一些基础的设置代码_第4页
安卓开发一些基础的设置代码_第5页
已阅读5页,还剩23页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

安卓开发一些基础的设置代码DialogFragment设置背景透明onCreateView Window window = getDialog().getWindow(); if (window != null) window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT); 简单的btn状态选择器 Fragment和Activity的交互需要注意的是 getActivity() 有可能会返回nullView xxx = getActivity().findViewById(R.id.xxx);获得fragment的引用要用FragmentManager,之后可以调用findFragmentById() 或者 findFragmentByTag()ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);事件回调一些情况下,可能需要fragment和activity共享事件,一个比较好的做法是在fragment里面定义一个回调接口,然后要求activity实现它,当activity通过这个接口接收到一个回调,它可以同布局中的其他fragment分享这个信息。监听Fragment Back的两个方法 写回调实现 判断RootView Override public void onResume() super.onResume(); getView().setFocusableInTouchMode(true); getView().requestFocus(); getView().setOnKeyListener(new View.OnKeyListener() Override public boolean onKey(View v, int keyCode, KeyEvent event) if (event.getAction() = KeyEvent.ACTION_UP & keyCode = KeyEvent.KEYCODE_BACK) / handle back button return true; return false; ); 调用市场playUri uri = Uri.parse(market:/details?id= + context.getPackageName();Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);try startActivity(goToMarket); catch (ActivityNotFoundException e) 自定义View(1)定义一个Class继承于系统View;(2)在xml中配置layout布局文件;(3)重写父类的一些方法,如onMeasure、onDraw、onLayout等;(4)在程序中应用自定义的View;onMeasure()用来设置视图的大小,即视图的宽度和高度onLayout()用于设置视图在屏幕中显示的位置onDraw()利用前面两部分得到的参数,将视图显示在屏幕上android的设计模式模版模式每次新建一个Activity时都会覆盖onCreate(),onStart()方法等,这些方法在父类中就相当于一个模板观察者模式点击事件适配器模式adapter单例模式Application工厂模式BitmapFactory.decodeResource();BitmapFactory相当于位图工厂代理模式AIDLLayout属性android:clipToPadding:配合paddingTop可简单实现View距离顶部一定距离android:clipChildren:是否限制子View在其范围内调用显示触摸位置功能vider.Settings.System.putInt(getContentResolver(), show_touches, 1);代码切换全屏 /切换到全屏 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); /切换到非全屏 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);Activity透明 android:color/transparent null true true null展开、收起状态栏 public static final void collapseStatusBar(Context ctx) Object sbservice = ctx.getSystemService(statusbar); try Class statusBarManager = Class.forName(android.app.StatusBarManager); Method collapse; if (Build.VERSION.SDK_INT = Build.VERSION_CODES.JELLY_BEAN_MR1) collapse = statusBarManager.getMethod(collapsePanels); else collapse = statusBarManager.getMethod(collapse); collapse.invoke(sbservice); catch (Exception e) e.printStackTrace(); public static final void expandStatusBar(Context ctx) Object sbservice = ctx.getSystemService(statusbar); try Class statusBarManager = Class.forName(android.app.StatusBarManager); Method expand; if (Build.VERSION.SDK_INT = 17) expand = statusBarManager.getMethod(expandNotificationsPanel); else expand = statusBarManager.getMethod(expand); expand.invoke(sbservice); catch (Exception e) e.printStackTrace(); 获取网络类型名称 public static String getNetworkTypeName(Context context) if (context != null) ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectMgr != null) NetworkInfo info = connectMgr.getActiveNetworkInfo(); if (info != null) switch (info.getType() case ConnectivityManager.TYPE_WIFI: return WIFI; case ConnectivityManager.TYPE_MOBILE: return getNetworkTypeName(info.getSubtype(); return getNetworkTypeName(TelephonyManager.NETWORK_TYPE_UNKNOWN); public static String getNetworkTypeName(int type) switch (type) case TelephonyManager.NETWORK_TYPE_GPRS: return GPRS; case TelephonyManager.NETWORK_TYPE_EDGE: return EDGE; case TelephonyManager.NETWORK_TYPE_UMTS: return UMTS; case TelephonyManager.NETWORK_TYPE_HSDPA: return HSDPA; case TelephonyManager.NETWORK_TYPE_HSUPA: return HSUPA; case TelephonyManager.NETWORK_TYPE_HSPA: return HSPA; case TelephonyManager.NETWORK_TYPE_CDMA: return CDMA; case TelephonyManager.NETWORK_TYPE_EVDO_0: return CDMA - EvDo rev. 0; case TelephonyManager.NETWORK_TYPE_EVDO_A: return CDMA - EvDo rev. A; case TelephonyManager.NETWORK_TYPE_EVDO_B: return CDMA - EvDo rev. B; case TelephonyManager.NETWORK_TYPE_1xRTT: return CDMA - 1xRTT; case TelephonyManager.NETWORK_TYPE_LTE: return LTE; case TelephonyManager.NETWORK_TYPE_EHRPD: return CDMA - eHRPD; case TelephonyManager.NETWORK_TYPE_IDEN: return iDEN; case TelephonyManager.NETWORK_TYPE_HSPAP: return HSPA+; default: return UNKNOWN; 扫描指定的文件sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);有没有应用程序处理你发出的intentpublic static boolean isIntentAvailable(Context context, String action) final PackageManager packageManager = context.getPackageManager(); final Intent intent = new Intent(action); List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() 0;TransitionDrawable实现渐变效果private void setImageBitmap(ImageView imageView, Bitmap bitmap) final TransitionDrawable td = new TransitionDrawable(new Drawablenew ColorDrawable(R.color.colorAccent), new BitmapDrawable(imageView.getContext().getResources(), bitmap); imageView.setBackgroundDrawable(imageView.getDrawable(); imageView.setImageDrawable(td); td.startTransition(200);字符串中只能包含:中文、数字、下划线(_)、横线(-)public static boolean checkNickname(String sequence) final String format = u4E00-u9FA5uF900-uFA2Dw-_; Pattern pattern = Ppile(format); Matcher matcher = pattern.matcher(sequence); return !matcher.find();字符串中是否包含汉字public static boolean checkChinese(String sequence) final String format = u4E00-u9FA5uF900-uFA2D; boolean result = false; Pattern pattern = Ppile(format); Matcher matcher = pattern.matcher(sequence); result = matcher.find(); return result;获取应用程序下所有Activitypublic static ArrayList getActivities(Context ctx) ArrayList result = new ArrayList(); Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.setPackage(ctx.getPackageName(); for (ResolveInfo info : ctx.getPackageManager().queryIntentActivities(intent, 0) result.add(info.activityI); return result;计算字宽注意如果设置了textStyle,还需要进一步设置TextPaintpublic static float GetTextWidth(String text, float Size) TextPaint FontPaint = new TextPaint(); FontPaint.setTextSize(Size); return FontPaint.measureText(text);判断是否是平板public static boolean isTablet(Context context) return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) = Configuration.SCREENLAYOUT_SIZE_LARGE;获取屏幕尺寸public static double getScreenPhysicalSize(Activity ctx) DisplayMetrics dm = new DisplayMetrics(); ctx.getWindowManager().getDefaultDisplay().getMetrics(dm); double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2); return diagonalPixels / (160 * dm.density);代码设置TextView的样式new TextView(new ContextThemeWrapper(this, R.style.text_style)TextView 显示文字阴影效果1. TextView.setShadowLayer(10F, 11F,5F, Color.YELLOW); 第一个参数为模糊半径,越大越模糊。 第二个参数是阴影离开文字的 x 横向距离。 第三个参数是阴影离开文字的 Y 横向距离。 第四个参数是阴影颜色。2. 将 TextView 控件的 style 单独写成一个. xml 文件进行添加CRUD语句insert:insert into tab_name (field,field,field) values(?,?,?)update:update tab_name set field = value where field = valueselect:select * from tab_namedelete:delete from tab_name where field = value简单的四个语句,复杂的需要自己添加,例如select时候可以添加where实现过滤功能AlertDialog改变ThemeAlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom);截取当前屏幕截图public static Bitmap captureContent(Activity activity) View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache(); Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; int width = activity.getWindowManager().getDefaultDisplay().getWidth(); int height = activity.getWindowManager().getDefaultDisplay().getHeight(); Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return b;textView显示不同颜色public static SpannableStringBuilder getHomeTitlePageType(String text, String suffix) SpannableStringBuilder mText = new SpannableStringBuilder(# + text + # + suffix); ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(ContextCompat.getColor(App.getContext(), R.color.colorPrimary); mText.setSpan(foregroundColorSpan, 0, mText.length() - suffix.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return mText;关闭软键盘public static void offKeyboard(EditText editText) if (detectKeyboard(editText) InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); public static void openKeyboard(EditText editText) if (!detectKeyboard(editText) InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT); public static boolean detectKeyboard(EditText editText) /true 弹出状态 InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); return imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);代码创建selectorpublic class SelectorUtils public static StateListDrawable getDrawableSelector(float enabledRadius, int enabledColor, float normalRadius, int normalColor) StateListDrawable drawable = new StateListDrawable(); drawable.addState(new intandroid.R.attr.state_enabled, getShape(enabledRadius, enabledColor); drawable.addState(new int-android.R.attr.state_enabled, getShape(normalRadius, normalColor); return drawable; private static GradientDrawable getShape(float radius, int color) GradientDrawable gd = new GradientDrawable(); gd.setShape(GradientDrawable.OVAL); gd.setCornerRadius(radius); gd.setColor(color); return gd; 双击退出程序private long exitTime = 0; Override public void onBackPressed() if (System.currentTimeMillis() - exitTime) 2000) Toast.makeText(getApplicationContext(), 再按一次退出, Toast.LENGTH_LONG).show(); exitTime = System.currentTimeMillis(); else super.onBackPressed(); 检测用户是否某个应用 public static boolean isApk(Context context, String packageName) final PackageManager packageManager = context.getPackageManager(); List pinfo = packageManager.getInstalledPackages(0); if (pinfo != null) for (int i = 0; i pinfo.size(); i+) String pn = pinfo.get(i).packageName; if (pn.equals(packageName) return true; return false; 在代码中改变TextView的drawable的图片资源Drawable drawable = getResources().getDrawable(R.mipmap.ic_pay_koukuan); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight(); tv_text.setCompoundDrawables(drawable, null, null, null); 点击按钮实现手机震动 public static void vibrator(Context context) Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); /控制振动时间 vibrator.vibrate(2000); EditText输入限制小数点后两位public class EditTextUtils public static void editWatcher(final EditText editText, final EditTextChanged editTextChanged) editText.addTextChangedListener(new TextWatcher() Override public void beforeTextChanged(CharSequence s, int start, int count, int after) editTextChanged.beforeTextChanged(); Override public void onTextChanged(CharSequence s, int start, int before, int count) if (s.toString().contains(.) if (s.length() - 1 - s.toString().indexOf(.) 2) s = s.toString().subSequence(0, s.toString().indexOf(.) + 3); editText.setText(s); editText.setSelection(s.length(); Override public void afterTextChanged(Editable s) ); public interface EditTextChanged void beforeTextChanged(); TextView后加字体并改变颜色点击跳转private void hint_onClick() SpannableString span = new SpannableString(hint);/后加内容 ClickableSpan click = new MClickableSpan(this); span.setSpan(click, 0, hint.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); tvHint.append(span); tvHint.setMovementMethod(LinkMovementMethod.getInstance(); public class MClickableSpan extends ClickableSpan Override public void updateDrawState(TextPaint ds) ds.setColor(Color.BLUE); Override public void onClick(View widget) apk下载完成跳转到安装界面public static void installApp(Context context, String filePath) File _file = new File(filePath); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(_file),application/vnd.android.package-archive); context.startActivity(intent);添加删除桌面快捷方式/* * 创建桌面快捷方式 */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, new Intent(Intent.ACTION_MAIN).setComponent(comp); Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.mipmap.ic_launcher); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); sendBroadcast(shortcut);/* * 删除程序的快捷方式 */private void delShortcut() Intent shortcut = new Intent(com.android.launcher.action.UNINSTALL_SHORTCUT); shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name); /指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer /注意: ComponentName的第二个参数必须是完整的类名(包名+类名),否则无法删除快捷方式 String appClass = this.getPackageName() + . + this.getLocalClassName(); ComponentName comp = new ComponentName(this.getPackageName(), appClass); shortcut.putEx

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论