此文隨時更新,旨在記錄平時遇到的不值得單獨寫博客記錄的細節問題,當然如果問題有拓展將會另外寫博客。
原文地址請保留http://www.cnblogs.com/rossoneri/p/4040314.html
1.xml中layout_gravity,gravity的區別。
layout_gravity表示控件自身位置,gravity表示子組件的位置。
2.加imageView后提示Warning:Missing content Description attribute on image
Resolved this warning by setting attribute android:contentDescription
for my ImageView
android:contentDescription="@string/desc"
Android Lint support in ADT 16 throws this warning to ensure that image widgets provide a contentDescription.
This defines text that briefly describes content of the view. This property is used primarily for accessibility. Since some views do not have textual representation this attribute can be used for providing such.
Non-textual widgets like ImageViews and ImageButtons should use the contentDescription attribute to specify a textual description of the widget such that screen readers and other accessibility tools can adequately describe the user interface.
http://stackoverflow.com/questions/8500544/android-lint-contentdescription-warning
3.eclipse編譯時長時間refreshing external folders導致等待時間過長
選擇project->properties
選擇Java build path->libraries->android.jar->source attachment,remove掉Source attachment中的路徑
4.如何往 AlertDialog 的 title 上增加按鈕?
不能加按鈕之類的控件,title 只能設置內容,顏色,背景。如果想加?那就這樣:仿照你需要的效果畫一個 layout 出來,然后寫一個類A inflate 這個 layout,之后再定義一個 AlertDialog ,
用 builder.setView(A.getViewGroup) 就可以了,最后 show() 出來。提醒一句,不要 builder.setTitle() 了,不設置 title 的內容 AlertDialog 就不會顯示 title 欄,下面的三個按鈕也一樣。
下面放個效果圖: (找時間再專門寫一個小demo吧)

5.使用 GridView 如何獲取 item 單擊事件?
mGridShowThumbnail.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub } });
position 就是單擊的 item 的序號
但是如果 item 是組合控件,比如說 imageview 和 checkbox ,要實現單擊兩個控件實現不同效果,這樣就不可以,需要對 item 的兩個控件分別寫各自的事件。
6.Android 項目 clean 后 R 文件不生成?
一般 clean 后重新 build 會自動生成 R 文件,沒生成基本上是 xml 文件有錯誤。把錯誤改一下就好。
7.android:layout_toLeftOf=“@id/x”
這個id一定要在這個控件之前聲明,不能寫在后面,否則會報錯。(我是這么覺得。。)
8.將應用程序最小化
mActivity.moveTaskToBack(false);
boolean android.app.Activity.moveTaskToBack(boolean nonRoot) public boolean moveTaskToBack (boolean nonRoot) Added in API level 1 Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged. Parameters nonRoot If false then this only works if the activity is the root of a task; if true it will work for any activity in a task. Returns If the task was moved (or it was already at the back) true is returned, else false.
9.最小化后在 serivce 里再將其恢復窗口
Intent intent = new Intent(getBaseContext(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplication().startActivity(intent);
10.設置背景用setbackgroundXXX,那去掉背景用什么,沒有相關的remove方法啊?
mLayout.setBackgroundColor(getResources().getColor(R.color.pic_bg)); // 設置背景色要注意寫法
mLayout.setBackgroundResource(0); // 去掉背景
關於去掉背景,參見文檔
public void setBackgroundResource (int resid)
Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.
11.刷新GridView的內容
mAdapter.notifyDataSetChanged();
public void notifyDataSetChanged ()
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
12.DDMS下使用 Traceview 查看程序運行時間 (Android2.2+)
1,在設備表中選中你想進行method trace的進程。 2,單擊Start Method Profiling按鈕開始method trace。 3,method trace進行中。 4,單擊Stop Method Profiling按鈕停止method trace。緊接着系統會自動彈出Traceview窗口來顯示剛才的method trace結果。

13.如何獲取程序從后台回到前台的狀態信息來做響應事件?
這種情況基本上都用到service,從前台轉到后台,然后在service中做一些處理,然后程序回到前台后獲得到前台的信息,做關閉service等處理。
我是用到了截屏功能:程序轉到后台,service開啟浮動按鈕來自由截屏,如果截屏期間再點到原來的程序,就要獲取程序回到前台這個狀態,根據這個狀態把service的按鈕關掉。
處理這個的思路就是service開啟后就每隔一段時間(1s-2s)做一次檢查,檢查系統啟動的app隊列,從隊列中找到自己activity,然后對狀態進行判斷是在前台還是后台:
private ActivityManager mActivityManager; private String mPackageName; private void init(){ mActivityManager = (ActivityManager) mNetworkService .getSystemService(Context.ACTIVITY_SERVICE); mPackageName = mNetworkService.getPackageName(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { while (true) { Thread.sleep(1000); if (isAppOnForeGround()) { mScreenHandler.sendEmptyMessage(SCREENSHOT_DONE + 2); break; } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } private boolean isAppOnForeGround() { List<RunningAppProcessInfo> runningAppProcesses = mActivityManager.getRunningAppProcesses(); for (RunningAppProcessInfo processInf : runningAppProcesses) { if (processInf.processName.equals(mPackageName)) { if (processInf.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) return true; else return false; } } return false; }
感謝:Android 判斷程序前后台狀態
14. java異常:ConcurrentModificationException
這個問題是說,你不能在對一個List進行遍歷的時候將其中的元素刪除掉 解決辦法是,你可以先將要刪除的元素用另一個list裝起來,等遍歷結束再remove掉 可以這樣寫 List delList = new ArrayList();//用來裝需要刪除的元素 for(Information ia:list) if(ia.getId()==k){ n++; delList.add(ia); } list.removeAll(delList);//遍歷完成后執行刪除
參考百度知道
15. DashPathEffect
android.graphics.DashPathEffect.DashPathEffect(float[] intervals, float phase) The intervals array must contain an even number of entries (>=2), with the even indices specifying the "on" intervals, and the odd indices specifying the "off" intervals. phase is an offset into the intervals array (mod the sum of all of the intervals). The intervals array controls the length of the dashes. The paint's strokeWidth controls the thickness of the dashes. Note: this patheffect only affects drawing with the paint's style is set to STROKE or STROKE_AND_FILL. It is ignored if the drawing is done with style == FILL. Parameters: intervals array of ON and OFF distances phase offset into the intervals array 參數間隔數組(條目數>=2)必須包含一個偶數,其中偶數列代表“打開”間隔,奇數列代表“關閉”間隔。 參數相位是間隔數組內的偏移(對所有間隔之和取模)。間隔數組控制連接符的長度。Paint的邊寬度控制連接符的寬度。 大概用法: // draw dotted line paint.setStyle(Paint.Style.STROKE); paint.setColor(Color.GRAY); Rect rcDot = new Rect(); rcDot.left = 20; rcDot.top = 20; rcDot.right = bkWidth - 20; rcDot.bottom = bkHeight - 20; PathEffect effects = new DashPathEffect(new float[] { 10, 5 }, 1); paint.setPathEffect(effects); canvas.drawRect(rcDot, paint);
間隔數組是{10, 5} 效果為 —— —— —— —— —— 即實線和空白為2:1的關系
間隔數組是{10, 5, 3, 2} 效果為 ————— —— ————— —— 大概就是這個效果
16. popupwindow的小問題
mPopupMenu = new PopupWindow(mPopupMenuView, 220, ViewGroup.LayoutParams.WRAP_CONTENT); mPopupMenu.setOutsideTouchable(true); mPopupMenu.setBackgroundDrawable(new BitmapDrawable()); mPopupMenu.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { // TODO Auto-generated method stub mBtnMore.setChecked(false); } }); 寫了個菜單,點擊按鈕彈出。希望的效果是點擊菜單外部時菜單消失,同時改變按鈕狀態;點擊按鈕時,如果菜單彈出過了,也改變按鈕的狀態並且讓菜單消失。 但無情的是,這樣定義的popupwindow在顯示時,我如果再點擊按鈕,首先調用onDismissListener,然后才是按鈕事件,一直達不到我的效果。 然后我考慮,在popupwindow顯示的時候點擊按鈕,不再觸發按鈕事件,只觸發OnDismissListener,在查看popupwindow方法,試了試之后,發現需要定義下面的方法: mPopupMenu.setFocusable(true); 這樣在popupwindow顯示時,點擊外部,不會觸發外部的事件,只是關閉了彈出的對話框。 下面是方法文檔: void android.widget.PopupWindow.setFocusable(boolean focusable) Changes the focusability of the popup window. When focusable, the window will grab the focus from the current focused widget if the popup contains
a focusable android.view.View. By default a popup window is not focusable. If the popup is showing, calling this method will take effect only the next time the popup is shown or through a manual call to one of the update()
methods. Parameters: focusable true if the popup should grab focus, false otherwise.
17. The jar of this class file belongs to container 'Android Private Libraries' which does not allow modifications to source attachments on its entries.
查看外部依賴jar包的源代碼 這里假設你已經把外部依賴的jar包正確導入並且編譯通過了,但是ctrl+鼠標左鍵想看代碼或者想看其注釋卻不可行的情況, 首先在libs下面找到引入的包,這里以android-support-v4.jar為例, 在libs下新建android-support-v4.jar.properties文件,即與引用的jar包同名最后加上.properties的文件 其內容如下: src = E:\\eclipse\\sdk\\extras\\android\\support\\v4\\src 這里路徑要根據你自己的路徑進行調整,配置之后退出eclipse,在進入,就可以正常查看了。
參考:Android開發技巧之查看外部依賴jar的源碼_android private libralies does not allow modifications to source
18. 帶有默認文字的edittext,讓光標默認在文字后方
mEtName.setText(strAsName);
mEtName.setSelection(strAsName.length());
19.如何獲取Android設備的頂部狀態欄和底部工具欄的高度
20.如何設置AlertDialog的按鈕的可用狀態
21. Android文件名長度有限制么?
Android下文件名最長只能支持127個中文,不超過255個字符
路徑也算的,即使在windows下也是要算路徑的
Android無法讀取SD卡中名字太長的文件疑問
Android文件名長度有問題?
22. 獲取資源文件里的bitmap
BitmapDrawable draw=(BitmapDrawable)getResources().getDrawable(R.drawable.bitmap);
Bitmap m=draw.getBitmap();
23. Android設置屏幕方向
//自動轉屏 activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); //設置橫向 activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); //設置縱向 activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
24. 彈出有輸入框的對話框,讓軟鍵盤壓縮對話框顯示
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
dialog.show();
對於對話框,加上scrollview使顯示良好
<ScrollView android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" >
25. ubuntu不識別android設備
lsusb 查看設備信息 id信息添加到/etc/udev/rules.d/51-android.rules 再 /etc/init.d/udev restart 最后sdk工具目錄下 sudo ./adb kill-server sudo ./adb devices
26. 查看指定文件夾下某文件數量
File folder = new File(Path); File[] files = folder.listFiles(); for (int i = 0; i < files.length; ++i) { File file = files[i]; if (file.isFile()) { String[] str = file.getPath().split("\\."); if (str[1].equals("pdf")) { mStrNum++; } } else continue; }
其余相關獲取路徑/操作路徑的方法
android系統通過圖片絕對路徑獲取URI的三種方法
Android 如何讀取指定目錄下的音樂文件
android開發之Cursor方法的 使用及android遍歷
27. 軟鍵盤彈出對話框壓縮顯示
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
28.對話框監聽返回事件
dialog.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { dialog.dismiss(); return true; } else return false; } });
29.刪除系統內置程序
有的設備不能root,要刪除內置一些程序,用下面的方法:
adb shell su mount -o remount,rw rootfs /system/ cd /system/app ls rm XXXX.apk
30. adb: error while loading shared libraries: libstdc++.so.6: cannot open shared object file: No such file or directory
sudo apt-get install lib32stdc++6
31. linux 幾個 path
.bashrc
.profile
/etc/profile
32. ubuntu 下不識別 android 設備:
33. Android資源字符串內有變量
<string name="alert">我叫%1$s,我來自%2$s</string> <string name="old">我%1$d歲了</string>
String sFormat = getResources().getString(R.string.alert); String sFormat1 = getResources().getString(R.string.old); String sFinal = String.format(sFormat, "張三","上海"); String sFinal1 = String.format(sFormat1, 23);
34. ubuntu 關閉/打開筆記本觸摸板
#close sudo rmmod psmouse #open sudo modprobe psmouse
35. 獲取手指滑動閾值
這個值可以自己定,不過看到一個方法,獲得的值為8pix,應該是個標准
// Distance in pixels a touch can wander before we think the user is scrolling // int 相當於一個手指滑動的閾值 ViewConfiguration.get(getContext()).getScaledTouchSlop();
36. 獲取LayoutInflater
LayoutInflater inflater = LayoutInflater.context(this); LayoutInflater inflater = getLayoutInflater(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
37. wifi 密碼路徑 data/misc/wifi/wpa_supplicant.conf
38. TextView加下划線
mTvAddmore.setText(Html.fromHtml("<u>" + mStrAddMore + "</u>"));
39. RadioButton / CheckBox 按鈕顯示在文字后面
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
40. RadioButton / CheckBox 等設置系統風格
mCbAuto = (CheckBox) mView.findViewById(R.id.sort_auto); int id_cb = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android"); mCbAuto.setButtonDrawable(id_cb); or android:drawableRight="@drawable/btn_check_holo_light"