我的词典:即粘即用一

来源:互联网 发布:万人迷网络电话软件 编辑:程序博客网 时间:2024/04/30 03:37

<每篇 10 例>

实用一:

当点击EditText编辑框的时候,禁止手机的软键盘弹出;

editText.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubint inType = edtComment.getInputType(); // backup the input type  edtComment.setInputType(InputType.TYPE_NULL); // disable soft input      //edtComment.onTouchEvent(event); // call native handler      //edtComment.setInputType(inType); // restore input type     //edtComment.setSelection(edtComment.getText().length());  return true;}});

实用二:

手动显示软键盘隐藏软键盘:

当软键盘显示则使其隐藏,反之显示:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);


view为接受软键盘输入的视图,SHOW_FORCED表示强制显示:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘

调用隐藏系统默认的输入法:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WidgetSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);  (WidgetSearchActivity是当前的Activity)

获取输入法打开的状态:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);boolean isOpen=imm.isActive();//isOpen若返回true,则表示输入法打开

直接隐藏软键盘:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);//隐藏软键盘

实用三:

在使用View.settag()方法的时候,有两个重写的相同方法:View.gettag(Object obj) - View.gettag(int id, Object obj)  对于第二个方法,其中的int id  是有自己的要求的,需要满足int-id 是resource的;即:在   res/values/ids/***  路径下:

<?xml version="1.0" encoding="utf-8"?><resources>        <item type="id" name="convertview_item_id"></item>     <item type="id" name="convertView_gridviewItem_id"></item></resources>

然后调用即可:

privateComments.praise.setTag(R.id.convertview_item_id, privateComments.praiseNumber);


不然的话会报错的:

实用四

把resource下 int 类型的图片转化为 Drawable 类型:

final int normalId = R.drawable.btn_praise_normal;Drawable normalDrawable = context.getResources().getDrawable(normalId);

补充说明:实践证明,通过这个转化的方法,每使用一次 每次就像相当于又重新创建了一个新的对象,那么也就是说虽然是实用同一个 id 来转化的,但是已经属于各自不同的对象了。因此在使用“ == ”<getBackground() 与 normalDrawable 进行比较> 对再进行创建了新的对象进行比较,就不相同(只要是不同的对象),结果就是 "false"

实用五:

时间格式化。在做项目的时候总会时不时的遇到各种需求的时间格式规范的要求。那么下面就介绍一下几种留着自己以后粘贴使用:

/** 转换获取出入的字符串时间值<时间戳String>  <时间格式:10-08 11:01>*/public static String getStringTime(String strTime){SimpleDateFormat sd = new SimpleDateFormat("MM-dd"+"\0\0"+"HH:"+"mm");long sTime = Long.valueOf(strTime);return sd.format(new Date(sTime * 1000));}

 

/** 获取并格式化当前时间值<时间戳long> <时间格式:10-08 11:01> */public static String getCurrentTime(long date){SimpleDateFormat sd = new SimpleDateFormat("MM-dd"+"\t"+"HH:"+"mm");return sd.format(date);}

/** 转换获取出入的字符串时间值  <10-08>*/public static String getStringTimeDM(String strTime){SimpleDateFormat sd = new SimpleDateFormat("MM-dd");long sTime = Long.valueOf(strTime);return sd.format(new Date(sTime * 1000));}


 

/** 转换获取出入的字符串时间值<时间戳long>  <时间格式:10-08>*/public static String getStringTimeDM(String strTime){SimpleDateFormat sd = new SimpleDateFormat("MM-dd");long sTime = Long.valueOf(strTime);return sd.format(new Date(sTime * 1000));}

/** * 格式化发布时间于现在时间的时差 * @param publishTime * @return */public static String getStringTimePublished(Integer publishTime){final long month = 30 * 24 * 60 * 60 * 1000;    final long date = 24 * 60 * 60 * 1000;    final long hour = 60 * 60 * 1000;    final long minute = 60 * 1000;long sTime = Long.valueOf(publishTime);long tTime = System.currentTimeMillis();long nTime = tTime - sTime * 1000;if(nTime / (12 * month) > 1){return "发布于:"+(nTime / (12 * month))+"年前";}else if(nTime / month > 1){return "发布于:"+(nTime / month)+"个月前";} else if(nTime / date > 1){return "发布于:"+(nTime / date)+"天前";} else if(nTime / hour > 1){return "发布于:"+(nTime / hour)+"小时前";} else if(nTime / minute > 1){return "发布于:"+(nTime / minute)+"分钟前";} elsereturn "刚刚发布";}


 

/** * 格式化发布时间于现在时间的时差 * @param publishTime * @return         *<返回值是:发布于:xx小时前>   */public static String getStringTimePublished(Integer publishTime){final long month = 30 * 24 * 60 * 60 * 1000;    final long date = 24 * 60 * 60 * 1000;    final long hour = 60 * 60 * 1000;    final long minute = 60 * 1000;long sTime = Long.valueOf(publishTime);long tTime = System.currentTimeMillis();long nTime = tTime - sTime * 1000;if(nTime / (12 * month) > 1){return "发布于:"+(nTime / (12 * month))+"年前";}else if(nTime / month > 1){return "发布于:"+(nTime / month)+"个月前";} else if(nTime / date > 1){return "发布于:"+(nTime / date)+"天前";} else if(nTime / hour > 1){return "发布于:"+(nTime / hour)+"小时前";} else if(nTime / minute > 1){return "发布于:"+(nTime / minute)+"分钟前";} elsereturn "刚刚发布";}


实用六:

 ListView长按弹出菜单:这里是长按弹出上下文,且只能是这种情况。那么,具体实现代码:

//第一步:设置监听listView.setOnCreateContextMenuListener(this);
//第二步:重写方法<pre class="java" name="code">@Override      public void onCreateContextMenu(ContextMenu menu, View v,              ContextMenuInfo menuInfo) {              menu.setHeaderTitle("确定要删除吗?");              //添加菜单项              menu.add(0,1,0,"确定");              menu.add(1,2,0,"取消");          super.onCreateContextMenu(menu, v, menuInfo);      }            @Override      public boolean onContextItemSelected(MenuItem item) {          AdapterContextMenuInfo info=(AdapterContextMenuInfo)item.getMenuInfo();          int po = info.position;                switch (item.getItemId()) {case 1:Toast.makeText(getApplicationContext(), "确定"+po, 1).show();break;case 2:Toast.makeText(getApplicationContext(), "取消"+po, 1).show();break;default:break;}        return super.onContextItemSelected(item);      }  

//第二部重写方法@Override      public void onCreateContextMenu(ContextMenu menu, View v,              ContextMenuInfo menuInfo) {              menu.setHeaderTitle("确定要删除吗?");              //添加菜单项              menu.add(0,1,0,"确定");              menu.add(1,2,0,"取消");          super.onCreateContextMenu(menu, v, menuInfo);      }            @Override      public boolean onContextItemSelected(MenuItem item) {          AdapterContextMenuInfo info=(AdapterContextMenuInfo)item.getMenuInfo();          int po = info.position;                switch (item.getItemId()) {case 1:Toast.makeText(getApplicationContext(), "确定"+po, 1).show();break;case 2:Toast.makeText(getApplicationContext(), "取消"+po, 1).show();break;default:break;}        return super.onContextItemSelected(item);      }  

然后是实用第二种方法:通过设置listView自有的长按监听那么,看代码:

//第一步:设置监听listView.setOnItemLongClickListener(this);



 

//第二步:在监听的方法中创建对话框并作响应的处理@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View view,final int position, long id) {// TODO Auto-generated method stubif(TextUtils.isEmpty(userToken))return false;final AlertDialog.Builder builder = new Builder(getActivity());builder.setMessage("确定删除?"+listBean.get(position).getId());builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubdialog.dismiss();}});builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubif(OperationTool.isNetWorkConnected(getActivity())){get(mHandler, UrlFinalcons.urlDeleteDnamic+"token="+userToken+"&id="+listBean.get(position).getId(), NormalFinalcons.DELETE_DYNAMIC);}dialog.dismiss();}});builder.show();return false;}


 实用七:

在我们编写程序的时候,我们会经常遇到这样一个问题:我想要把一个对象在两个Activity之间进行传递,这样到目前为止我就知道两种方法。方法一:使用序列化,把对象转化为json字符串在两者之间进行传递,接收到之后再进行反序列化得到该对象;方法二:直接在bean上就对该对象进行序列化实现"Parcelable"接口,使用多态进行传递;

由于第一种方法较简单,那么我所要说的就是使用第二种方法:

什么也不用讲,直接贴代码,最清楚不过了:

public class GoodsBean implements Parcelable {private int goods_id;private String goods_image;private String goods_name;private double new_price;private double old_price;private double praise_scale;private int scales_volume;private String create_time;private String goods_promotion;private String goods_location;public GoodsBean() {super();}private String s_sub_category;private String sub_category;private String category;public int getGoods_id() {return goods_id;}public void setGoods_id(int goods_id) {this.goods_id = goods_id;}public String getGoods_image() {return goods_image;}public void setGoods_image(String goods_image) {this.goods_image = goods_image;}public String getGoods_name() {return goods_name;}public void setGoods_name(String goods_name) {this.goods_name = goods_name;}public double getNew_price() {return new_price;}public void setNew_price(double new_price) {this.new_price = new_price;}public double getOld_price() {return old_price;}public void setOld_price(double old_price) {this.old_price = old_price;}public double getPraise_scale() {return praise_scale;}public void setPraise_scale(double praise_scale) {this.praise_scale = praise_scale;}public int getScales_volume() {return scales_volume;}public void setScales_volume(int scales_volume) {this.scales_volume = scales_volume;}public String getCreate_time() {return create_time;}public void setCreate_time(String create_time) {this.create_time = create_time;}public String getGoods_promotion() {return goods_promotion;}public void setGoods_promotion(String goods_promotion) {this.goods_promotion = goods_promotion;}public String getGoods_location() {return goods_location;}public void setGoods_location(String goods_location) {this.goods_location = goods_location;}public String getS_sub_category() {return s_sub_category;}public void setS_sub_category(String s_sub_category) {this.s_sub_category = s_sub_category;}public String getSub_category() {return sub_category;}public void setSub_category(String sub_category) {this.sub_category = sub_category;}public String getCategory() {return category;}public void setCategory(String category) {this.category = category;}public GoodsBean(int goods_id, String goods_image, String goods_name,double new_price, double old_price, double praise_scale,int scales_volume, String create_time, String goods_promotion,String goods_location, String s_sub_category, String sub_category,String category) {super();this.goods_id = goods_id;this.goods_image = goods_image;this.goods_name = goods_name;this.new_price = new_price;this.old_price = old_price;this.praise_scale = praise_scale;this.scales_volume = scales_volume;this.create_time = create_time;this.goods_promotion = goods_promotion;this.goods_location = goods_location;this.s_sub_category = s_sub_category;this.sub_category = sub_category;this.category = category;}public GoodsBean(int goods_id, String goods_image, String goods_name,double new_price, double old_price, double praise_scale,int scales_volume, String create_time, String goods_promotion,String goods_location) {super();this.goods_id = goods_id;this.goods_image = goods_image;this.goods_name = goods_name;this.new_price = new_price;this.old_price = old_price;this.praise_scale = praise_scale;this.scales_volume = scales_volume;this.create_time = create_time;this.goods_promotion = goods_promotion;this.goods_location = goods_location;}@Overridepublic String toString() {return "GoodsBean [goods_id=" + goods_id + ", goods_image="+ goods_image + ", goods_name=" + goods_name+ ", new_price=" + new_price + ", old_price=" + old_price+ ", praise_scale=" + praise_scale + ", scales_volume="+ scales_volume + ", create_time=" + create_time+ ", goods_promotion=" + goods_promotion + ", goods_location="+ goods_location + ", s_sub_category=" + s_sub_category+ ", sub_category=" + sub_category + ", category=" + category+ "]";}@Overridepublic int describeContents() {// TODO Auto-generated method stubreturn 0;}public void writeToParcel(Parcel out, int flags) {out.writeInt(goods_id);out.writeString(goods_name);out.writeString(goods_image);out.writeDouble(new_price);out.writeDouble(old_price);out.writeDouble(praise_scale);out.writeInt(scales_volume);out.writeString(create_time);out.writeString(goods_promotion);out.writeString(goods_location);out.writeString(s_sub_category);out.writeString(sub_category);out.writeString(category);}public static final Parcelable.Creator<GoodsBean> CREATOR = new Parcelable.Creator<GoodsBean>() {public GoodsBean createFromParcel(Parcel in) {return new GoodsBean(in);}public GoodsBean[] newArray(int size) {return new GoodsBean[size];}};private GoodsBean(Parcel in) {goods_id = in.readInt();goods_image = in.readString();goods_name = in.readString();new_price = in.readDouble();old_price = in.readDouble();praise_scale = in.readDouble();scales_volume = in.readInt();create_time = in.readString();goods_promotion = in.readString();goods_location = in.readString();s_sub_category = in.readString();sub_category = in.readString();category = in.readString();}}

实用八:

fragment进行切换时候,请不要使用replace()方法。使用add()、hide() 方法!操作如下:

   FragmentTransaction transaction = getSupportFragmentManager().begainTransaction();   Fragment man = new Fragment()(AFragment);   Fragment girl = new Fragment()(BFragment);   if(man != girl){   if(girl.isAdded){      transaction.hide(man).show(girl).commit();   }else{      transaction.hide(man).add(R.id.content, girl).commit();         }   }
实用九:

相信很多人会遇到和我一样的情况!什么情况的bug呢?

在一个页面通过webview加载数据来展示页面的内容。但是由于网页内容是直接通过服务器转手给我的,也就是说我收到并要进行展示的网页内容是由后台编辑部的人做的,以展示在web上的网页内容。但是展示在我的Android设备上,图片肯定会不适配!!然后,问题就出来了—— ——挖掘机到底哪家强??

那么,我就开始网上搜索了......

也是搞了三天,才整理出来!当你不能解决上面的bug时。首先,你会先搜索到这几句代码:

                webView.requestFocus();webView.getSettings().setDefaultTextEncodingName("UTF-8") ;webView.getSettings().setJavaScriptEnabled(true);//支持JavaScript                webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
上面的几句代码,只使用与Android4.4以下(不包含Android4.4);那Android4.4之后怎么办呢?这里我使用的是与js交互来控制自己使用webview加载过来的内容图片,并使用js来改变图片的属性。看代码(Android4.4之前建议使用google的来控制,就是上面的代码),这里使用了上面的代码和js共同作用html图片。
/** * 通过webview展示html内容:解决图片过大通过js交互解决bug */private void displaytWebViewContent(){webView.requestFocus();webView.getSettings().setDefaultTextEncodingName("UTF-8") ;webView.getSettings().setJavaScriptEnabled(true);String release = android.os.Build.VERSION.RELEASE; // android系统版本号release = release.substring(0, 3); //Android 4.4图片显示不全if(!"4.4".equalsIgnoreCase(release)){webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);}else{displayWebViewContentBelowHighDpi();}}      /** * 如果Android系统高于4.4即SDK>=19时 */private void displayWebViewContentBelowHighDpi(){webView.setWebViewClient(new WebViewClient() {@Overridepublic void onPageFinished(WebView view, String url) {// TODO Auto-generated method stubview.setWebChromeClient(new WebChromeClient());view.loadUrl("javascript:(function(){"+ "var objs = document.getElementsByTagName(\"img\"); "+ "for(var i=0;i<objs.length;i++) {" +UrlFinalcons.js + "}"+ "})()");super.onPageFinished(view, url);}});webView.loadData(info.getContent(), "text/html; charset=UTF-8", null);}












可能会有人已经写过了自己的控制图片的JS代码,但是就是不明白应该放到哪里!哎,比如我就是这样。最后,终于在好兄弟的帮助下搞明白了!当然,你也可以在JS的代码中来判断Android到底应该在那个SDK等级来做处理。比如:

                                           view.loadUrl("javascript:(function(){"+ "var objs = document.getElementsByTagName(\"img\"); "+ "for(var i=0;i<objs.length;i++) {" + "if("+ VERSION.SDK_INT + ">=19){"+ "objs[i].style.width=320+ 'px';"+ "objs[i].style.height=180+ 'px';" + "}" + "}"+ "})()");
那么再贴一下自己写的JS代码:
public static final String js = "(function(f,o,w,h){for(var i=0;i<o.length;i++)f(o[i],w,h);})" +"(function(i,w,h){var _w = i.width,_h = i.height;" +"if (0==_w||0==_h)return;" +"((_w/_h>= w/h)&&(_w>w)&&(_h=(_h*w)/_w)&&(_w=w))||((_h>h)&&(_w=(_w*h)/_h)&&(_h=h));" +"(i.width=_w)&&(i.height=_h);" +"},document.getElementsByTagName('img'),320,180);";
好了,就这么多!ok了。





























实用十:

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {// TODO Auto-generated method stubif (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {// 当单击键盘的返回键时if (event.getAction() == KeyEvent.ACTION_DOWN) {       // ... 这里填写返回按键要处理的内容  ..<实用这种返回,较安全>}return super.onKeyDown(keyCode, event);

1 0
原创粉丝点击