记性不好,记录一些android开发中的东东

1.button设置背景图片为.9格式的时候发现文字被覆盖了,后来老郑说设置padding="0dp"就OK了,虽然还不知道为什么。(2014-9-22)

2.scrollview做弹性的时候内容不满屏,用权重布局有误,老郑说scrollview里+fillViewport属性就OK了。

3.获取获取当前系统的时间(东八区24小时制度)

public static String getPekingTime()
	{
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddkkmmss");  
		sDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		//String date = sDateFormat.format(new java.util.Date());
		return sDateFormat.format(new java.util.Date());
	}

4.字体适配(比较笨的方法,网上看的)

	/**
	 * 根据效果图的字体大小来适配
	 * 美工给的效果图为1080x1920(下面的/1920是根据高度算比例)
	 * @param context
	 * @param textSize //效果图上获取到字体的大小(px)
	 * @return
	 */
    public int getFontSize(Context context, int textSize) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        int screenHeight = dm.heightPixels;
        //screenWidth = screenWidth > screenHeight ? screenWidth :screenHeight;
        //int screenWidth = dm.widthPixels;
        //int rate = (int)(textSize*(float)screenWidth/1080);
        
        int rate = (int) (textSize * (float) screenHeight / 1920);
        return rate;
    }
使用方法:textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getFontSize(main_Fragment.getActivity(), 44));

5.用Fragment和tabhost做主界面,界面切换时会重新加载布局,网上有hide和show的方法,但我想界面切换或重新出现的时候onResume()会执行,

  hide和show的方法就不行了。网上有另一种方法:

	private View view;//缓存起来的布局避免每次切换都重新加载一遍
<span style="white-space:pre">	</span>@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(TAG, "onCreateView");
		if (view==null) {
			view = inflater.inflate(R.layout.account, container, false);
			
			//初始化控件之类的事
		}
		ViewGroup parentGroup=(ViewGroup) view.getParent();//缓存的view需要判断是否已经被加过parent, 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。
		if (parentGroup!=null) {
			parentGroup.removeView(view);
		}
		return view;
	}


6.EditText里hint字体大小修改(网上的)

	/**
	 * 修改edittext的hint字体大小
	 * @param editText
	 */
	public void changeedittexthint(EditText editText)
	{
		// 新建一个可以添加属性的文本对象
		//SpannableString ss = new SpannableString("喝酒就要喝一斤!");
		SpannableString ss = new SpannableString(editText.getHint());
		 
		// 新建一个属性对象,设置文字的大小
		AbsoluteSizeSpan ass = new AbsoluteSizeSpan(12, true);
		 
		// 附加属性到文本
		ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		
		// 设置hint
		editText.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
	}

7.一个界面有多个需要跳转到其他界面的intnet,搞成方法,传递activity对象

private void setintent(Class activity) {
		// TODO Auto-generated method stub
		startActivity(new Intent(context, activity));
	}
调用:
setintent(SecondActivity.class);

8.背景变暗,可用与一些弹框场景

设置为1f的时候变回原形

WindowManager.LayoutParams lp=getWindow().getAttributes();
lp.alpha = 0.4f;
getWindow().setAttributes(lp);

9.搞了个输入密码的AlertDialog弹框,跑起来的时候发现软键盘点不出来,百度了一下,选了个简单的方法:

http://blog.csdn.net/wy978651775/article/details/21026999

getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
	         WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

这是默认情况下隐藏软键盘的方法,要重新显示软键盘,要执行下面这段代码:

alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
AlertDialog.setView()则不会出现以上问题。
测试了可以一用,但软键盘如果自动跑出来效果更好些,有百度了一下:
http://ask.csdn.net/questions/208
里面的回答有两张可行的方法:
one:在编辑框上做文章
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			   @Override
			   public void onFocusChange(View v, boolean hasFocus) {
			       if (hasFocus) {
			            alertdialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
			       }
			   }
			});
two: 当创建了对话框之后你可以请求一个软件键盘
alertdialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

下面的是项目里的一个东东
dlg.setOnCancelListener(new OnCancelListener() {//防止不进行操作而直接取消弹出框而导致开关状态异常
				@Override
<span style="white-space:pre">				</span>public void onCancel(DialogInterface arg0) {
<span style="white-space:pre">					</span>// TODO Auto-generated method stub
<span style="white-space:pre">					</span>if (boolean) {
<span style="white-space:pre">						</span>slipswitch.setSwitchState(false);//检测按钮状态
<span style="white-space:pre">					</span>}else {
<span style="white-space:pre">						</span>slipswitch.setSwitchState(true);//检测按钮状态
<span style="white-space:pre">					</span>}//slipswitch.refreshDrawableState();//刷新开关按钮的布局(不知道这个为何不起作用)
<span style="white-space:pre">					</span>slipswitch.postInvalidate();//会调用控件的onDraw()重绘控件
<span style="white-space:pre">				</span>}
<span style="white-space:pre">			</span>});
http://blog.csdn.net/newcman/article/details/7782237

10.每次写注释里的时间和作者都要自己敲,略感麻烦,百度了一下:
windows-->preference-->Java-->Code Style-->Code Templates-->Comments-->Types-->右边的Edit按钮
将里面的东东替换为这个东东即可,当然名字改你自己的。(快捷键 shift+ alt+j)个人还是喜欢:/**+回车
/**
 * @author lzl
 * @date ${date} ${time}
 * ${tags}
 */

11.textview各种设置字体
http://blog.sina.com.cn/s/blog_9f233c0701012rdj.html
TextView mTextView = null;
 SpannableString msp = null;
 //设置字体大小(绝对值,单位:像素)   
 msp.setSpan(new AbsoluteSizeSpan(20), 4, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
 msp.setSpan(new AbsoluteSizeSpan(20,true), 6, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
//第二个参数boolean dip,如果为true,表示前面的字体大小单位为dip,否则为像素,同上。 
myTextView.setText(msp);

12.一直想搞类似QQ菜单的弹出的效果,不得其法,发现一篇可以实现的文章
    (Android 实现由下至上弹出并位于屏幕底部的提示框)
http://www.linuxidc.com/Linux/2012-04/59153.htm
 13.美工给了一套720的图片,一些大图怎么搞都适配不了多个屏幕,无法根据宽度适配高度。百度了N久,找到一个保存长宽比的的东东 
android:adjustViewBounds = "true"
http://blog.csdn.net/go12355/article/details/40301823
14.在activity里面让控件setAnimation动画正常启动,但放到工具类里面的时候就没反应了,看源码的注释也不明所以,百度良久,
     发现了setAnimation和startAnimation的区别(http://stackoverflow.com/questions/10909865/setanimation-vs-startanimation-in-android里的 user2024270推测是正确的)

     This is my understanding.SetAnimationwhen the view is added to the viewGroup,animation will be called.when the view has been added,the animation will not be calledStartAnimationanimation will be called all the time even though the view has been added.

15.<requestFocus />标签用于指定屏幕内的焦点View。

例如我们点击tab键或enter键焦点自动进入下一个输入框用法: 将标签置于Views标签内部

16.http://blog.csdn.net/pengchua/article/details/7582949(搞jni的)

17.eclipse写jni一直提示 Method 'NewStringUTF' could not be resolved

项目右键->属性->c/c++常规->Code Analysis,选择"Use project settings"  中的方法无法被解析(Method cannot be resolved)取消选择,应用->确定,然后刷新、清理、刷新、build项目。

18.jni输出日志(c++)#include <android/log.h>__android_log_print(ANDROID_LOG_INFO,"JNIMsg","ELEMENT %d IS %d\n",1,2);Android.mk里面添加LOCAL_C_INCLUDES := $(LOCAL_PATH)/include

LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog

19.美工的效果图要实现这种效果http://zilla.blog.51cto.com/3095640/984775

百思不得其解,后来QQ群有人发了这个地址,虽然我不知道里面的代码是什么意思,但我知道他的用意,修改一下,可以实现效果

计算好了之后调用这个方法即可

String temp = (String) TextUtils.ellipsize(txt, (TextPaint) paint,textLength, TextUtils.TruncateAt.END);

20.在代码里动态创建radiobutton,发现设置selector无效,百度了一下

设置颜色的selector,有两种方法

Resources resource = (Resources) context.getResources();  
	ColorStateList csl = (ColorStateList) resource.getColorStateList(R.color.dialog_radio_textcolor_selector); 
	radioButton.setTextColor(csl);
另一种:

	XmlPullParser xrp = context.getResources().getXml(R.color.dialog_radio_textcolor_selector);  
    try {  
        ColorStateList csl = ColorStateList.createFromXml(context.getResources(), xrp);  
        radioButton.setTextColor(csl);  
    } catch (Exception e) {  
    }
设置drawableRight的selector
<span style="white-space:pre">	</span>Drawable drawableRight = context.getResources().getDrawable(R.drawable.dialog_check_selector);
	drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(), drawableRight.getMinimumHeight());
	radioButton.setCompoundDrawables(null, null, drawableRight, null);
xml里的@button=null 就用radioButton.setButtonDrawable(android.R.color.transparent);

21.listview设置了适配器但适配器里的getview没有执行,百度了一下

ListView控件本身在xml中设置了gone也不会执行getView

22.要将List<Map<String, Object>> list对象保存在列表listStack里面,直接add(list),但后面有list.clear()的操作,这个listStack里面的也跟着清空了,看来listStack里保存的是引用了。老郑说用clone,百度了半天也是一头雾水。后来QQ群里有人说深复制可以用流形式,姑且一试,发现真的可以,就是不知道跟用迭代将list里的元素一个个抠出来哪个好用了。

public Object copy() throws IOException,ClassNotFoundException{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(你的对象);
		ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
		return ois.readObject();
	}
这个返回类型Object改成List<Map<String, Object>>,返回值也强转成List<Map<String, Object>>即可。

23.搞gridview的时候发现item填充父容器了,但跑起来发现四周有空隙,百度了一下

发现加上android:listSelector="@null"即可

24.用小米2S测试的时候,突然发现切换到横屏的时候竟然无效,在代码里使用setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

竟然卡死,吓了一跳。

百度了一下,http://www.cnblogs.com/jiutiandiwang/archive/2012/08/07/2627016.html

public void setRequestedOrientation(int requestedOrientation){
return;
}

加上这个方法就好了。

25.银联iso8583报文签到返回的62域为双倍长密钥3DES加密的密文,百度良久,找到了有人写好了的Java算法

http://zhangzxl.iteye.com/blog/1768571


26.ListView下拉刷新,当从其他界面跳回来的时候就去调用listview的下拉方法来更新数据,发现数据无法新数据获取下来了

但显示的还是旧的数据,找了一下,发现如果listview是最初始的位置的时候LogListView.setSelection(0),这个函数是无法更新listview的

最后还是得加上logAdapter.notifyDataSetChanged()才可以更新数据

27.EventBus主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息

http://blog.csdn.net/djun100/article/details/23762621

28.网页里的JS调用android里的方法,测试之后没问题就上线,结果就悲催了,有的手机竟然回调不了,后来百度良久,终于发现是版本的问题,

用4.12的手机测试没问题,用4.4的手机测就出问题,只要在android里的那个本地方法加个 @JavascriptInterface,再引入对应的包包就行了。

如:  

  @JavascriptInterface
  public void HTMLCALLANDROID(){
	//do something
  }

29.闲着没事抛一下异常

public class testexception {


<span style="white-space:pre">	</span>public static void main(String[] args) {
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">			</span>method1();
<span style="white-space:pre">		</span>} catch (Exception e) {
<span style="white-space:pre">			</span>// TODO: handle exception
<span style="white-space:pre">			</span>System.out.println(e.getMessage() + "\n" + e.getCause());
<span style="white-space:pre">		</span>}

<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>private static void method1() throws Exception {
<span style="white-space:pre">		</span>// TODO Auto-generated method stub
<span style="white-space:pre">		</span>method2();
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>private static void method2() throws Exception {
<span style="white-space:pre">		</span>// TODO Auto-generated method stub
<span style="white-space:pre">		</span>method3();
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>private static void method3() {
<span style="white-space:pre">		</span>// TODO Auto-generated method stub
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">			</span>int i = 1 / 0;
<span style="white-space:pre">		</span>} catch (Exception e) {
<span style="white-space:pre">			</span>// TODO: handle exception
<span style="white-space:pre">			</span>throw new IllegalArgumentException("method3 throws", e);
<span style="white-space:pre">		</span>}

<span style="white-space:pre">	</span>}
}

30. 关于休眠一下Android上用SystemClock.sleep(int); 而java上用Thread.sleep(int);,百度了一下,发现android上的最终还是调用了Java上的。

就是封装了一下而已吧。


31. 科学计数法转换成字符串

String sjiachun = "12345E-10";
BigDecimal db = new BigDecimal(sjiachun);//大数
String ii = db.toPlainString();

32.判断recyclerview是否滚到到了最后一项,百度良久,最后群里的人说的

在滚动监听里添加少许代码即可

LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
if (lm.findLastVisibleItemPosition() >= recyclerView.getAdapter().getItemCount() - 1) {
   //到最后一项了,没有到底
}


33.scrollview嵌套gridview,不滚了,就用来网上的方法:

    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);

    }
 发现进入界面的时候直接滚到底部了,见鬼了,百度良久,发现

scrollview.smoothScrollTo(0, 0);这个可以暂时用一下


34.因为虚拟键问题,搞到屏幕适配相对吐血,后老张说可以获取屏幕高度:

http://www.cnblogs.com/huxdiy/p/3977232.html

//获取屏幕尺寸,不包括虚拟功能高度<br><br>
getWindowManager().getDefaultDisplay().getHeight();
看了一下,发现方法过期了,百度了一下推荐的方法:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

获取屏幕原始尺寸高度,包括虚拟功能键高度,

private int getDpi(){
    int dpi = 0;

    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics dm = new DisplayMetrics();
    @SuppressWarnings("rawtypes")
    Class c;
    try {
        c = Class.forName("android.view.Display");
        @SuppressWarnings("unchecked")
        Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
        method.invoke(display, dm);
        dpi = dm.heightPixels;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dpi;
}
 
两个值相减即可得到虚拟键的高度。

35.android studio 从svn上检出项目,发现代码并没有在svn版本控制里吓了一大跳,百度一下svn的用法,发现点一下这个东东即可。

36.布局里要用背景图片来支撑高度,用linearlayout和relativelayout都不行,想到了framelayout ,试了一下,发现果然可以。

37.dialog在布局里设置全屏没有效果,设置一下即可
dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
38.http://my.oschina.net/liucundong/blog/354029?fromerr=KocmE0mO
外部html界面启动本地app
<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
 
        <title>this's a demo</title>
        <meta id="viewport" name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,minimal-ui">
    </head>
    <body>
        <div>
            <a id="J-call-app" href="javascript:;" class="label">立即打开>></a>
            <input id="J-download-app" type="hidden" name="storeurl" value="http://m.chanyouji.cn/apk/chanyouji-2.2.0.apk">
        </div>
 
        <script>
            (function(){
                var ua = navigator.userAgent.toLowerCase();
                var t;
                var config = {
                    /*scheme:必须*/
                    scheme_IOS: 'cundong://',
                    scheme_Adr: 'cundong://splash',
                    download_url: document.getElementById('J-download-app').value,
                    timeout: 600
                };
 
                function openclient() {
                    var startTime = Date.now();
 
                    var ifr = document.createElement('iframe');
 
 
                    ifr.src = ua.indexOf('os') > 0 ? config.scheme_IOS : config.scheme_Adr;
                    ifr.style.display = 'none';
                    document.body.appendChild(ifr);
 
                    var t = setTimeout(function() {
                        var endTime = Date.now();
 
                        if (!startTime || endTime - startTime < config.timeout + 200) { 
                            window.location = config.download_url;
                        } else {
                             
                        }
                    }, config.timeout);
 
                    window.onblur = function() {
                        clearTimeout(t);
                    }
                }
                window.addEventListener("DOMContentLoaded", function(){
                    document.getElementById("J-call-app").addEventListener('click',openclient,false);
 
                }, false);
            })()
        </script>
    </body>
</html>

AndroidMainfext.xml

<activity
     android:name=".activity.LauncherActivity"
     android:configChanges="orientation|keyboardHidden|navigation|screenSize"
     android:label="@string/app_name"
     android:screenOrientation="portrait" >
        <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:host="splash" android:scheme="cundong" />
       </intent-filter>
</activity>

39.scrollview嵌套webview,跳转链接的时候高度不一,容易出现底部空白的情况,百度一下
http://blog.csdn.net/self_study/article/details/47416565这个方法可以

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值