1. 用代碼設置ImageView的src和background
設置ImageView的src:
setImageDrawable(Drawable drawable);
setImageBitmap(Bitmap bm);
setImageResource(int resId);
代碼設置ImageView的background:
setBackgroundReource(int resid)
setBackground(Drawable background)
setBackgroundColor(int color)
setBackgroundDrawable(Drawable background) //This method was deprecated in API level 16. use setBackground(Drawable) instead
2. 在dimens.xml中保存不帶單位的數值
要在dimens.xml中保存不帶單位的數值,可以用如下格式來定義。
<item name="text_line_spacing" type="dimen" format="float">1.2</item>
在上述定義中,type=”dimen”屬性表示定義的item的資源類型是dimen類型。除了可以使用”dimen”外,還可以使用color,string,style等類型,但由于其他類型都可以直接定義,且沒有數值的約束,所以一般不需要通過這種方法來定義。format=”float”屬性表示定義的數值類型是float類型。除了”float”類型外,還可以使用boolean,fraction,integer等類型。例如:
<item name="top_weight" type="dimen" format="integer">5</item>
要在xml中引用上述定義的dimens,可以使用@dimen/text_line_spacing。
要在代碼中引用上述定義的dimens,可以使用如下代碼。
TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();
3. 在TextView中android:ellipsize="marquee"確保有效的方法
- xml設置
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
- 文字動態設置的話需要超出一行
- 在當前控件是visible的情況下textView.setSelected(true);
4. Android自定義Dialog設置有蒙版半透明背景的方法
<item name="android:backgroundDimEnabled">true</item>
<item name="android:backgroundDimAmount">0.42</item>
5. ScrollView中嵌套WebView時的焦點問題(ListView的item焦點搶奪同理)
外層使用ScroolView,內層嵌套使用WebView,每次進入Activity頁面時,整個頁面起始位置并不是頂部,這是因為WebView加載后獲得焦點導致的(ListView也會出現類似問題,即使修正了高度,也會主動獲得焦點,使得屏幕產生錯誤的滾動)
通過設置ScrollView包含的第一個viewgroup的
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants" >
viewgroup會覆蓋子類控件而直接獲得焦點來輕松解決問題。
6. 設置按鈕不可點擊
button.setEnabled(false);
或者
button.setClickable(false);
- 注意:
setClickable(false)方法一定要在setOnClickListener()方法之后用;
因為setOnClickListener()方法會重新繪制View;
7. 編輯框光標保持光標位于內容最后
setText之后設置:
etView.requestFocus();
否則先獲得了焦點,后續再設置內容,此時焦點肯定是放在內容之前的了,則就需要額外調用setSelection去調整位置了
etView.setSelection(etView.getText().toString().length());
8. ImageView擴大點擊區域
ImageView 直接設置其padding值達到目的,或者
android:scaleType="centerInside"
android:src="@drawable/ic_edit"
此時可以直接設置控件寬高來控制大小,注意不能用background,這會導致圖片變形
9. 禁止EditText自動獲取焦點
android:focusable="true"
android:focusableInTouchMode="true"
設置光標不可見
cursorVisible
10. TextView的文字也可以設置按下效果
新建 color/text_color_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white" android:state_pressed="true"></item>
<item android:color="@color/dail_black" android:state_pressed="false"></item>
</selector>
11. 一個控件設置TextView和兩個icon
<style name= "text_mine_line">
<item name="android:textSize">14dp</item>
<item name="android:textColor">@color/color_666666</item>
<item name="android:paddingStart">18dp</item>
<item name="android:paddingEnd">18dp</item>
<item name="android:drawableEnd">@mipmap/ic_more</item>
<item name="android:gravity">center_verticall</item>
<item name="android:drawablePadding">14dp</item>
<item name="android:background">@drawable/shape_line_gray</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">49dp</item>
</style>
12. 監聽ViewFlipper滑動的子View
public class MyViewFlipper extends ViewFlipper {
public MyViewFlipper(Context context) {
super(context);
}
public MyViewFlipper(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void showNext() { //從繼承關系中發現當子view變化的時候會調用該方法,因此在這里弄個回調
super.showNext();
mOnViewCountListener.viewCount(getDisplayedChild());
}
private OnViewCountListener mOnViewCountListener;
public void setOnViewCountListener(OnViewCountListener mOnViewCountListener)
{
this.mOnViewCountListener=mOnViewCountListener;
}
public interface OnViewCountListener{
void viewCount(int count);
}
}
13. 官方提供的自動改變文本大小的TextView
在XML中設置
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" // 加入app命名空間
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_45">
<android.support.v7.widget.AppCompatTextView
android:layout_width="@dimen/dimen_105"
android:layout_height="@dimen/dimen_32"
android:maxLines="1"
android:textSize="@dimen/dimen_sp_12"
android:textColor="@color/button_r_b_font_color"
app:autoSizeTextType="uniform" // 設置TextView大小設置樣式為支持改變(none時為不支持改變)
app:autoSizeStepGranularity="@dimen/lib_search_dimen_sp_1" // 每次改變的尺寸階梯
app:autoSizeMinTextSize="@dimen/lib_search_dimen_sp_8"
app:autoSizeMaxTextSize="@dimen/lib_search_dimen_sp_12" />
</RelativeLayout>
在代碼中動態設置
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_45">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/txt_price_section_item"
android:layout_width="@dimen/dimen_105"
android:layout_height="@dimen/dimen_32"
android:background="@drawable/red_black_selector_bg"
android:maxLines="1"
android:textSize="@dimen/dimen_sp_12"
android:textColor="@color/button_r_b_font_color" />
</RelativeLayout>
在代碼中進行改變字號的設置
TextViewCompat.setAutoSizeTextTypeWithDefaults(
textView, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(
textView, 8, 25, 1, TypedValue.COMPLEX_UNIT_SP);
- 控件的寬度和高度必須要有具體的值,不能設置為wrap_content
- 單行顯示需要使用maxLines="1"
14. 獲取控件寬高建議使用的方法
- 重寫Activity的onWindowFocusChanged方法,在該方法中獲取
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
//此處可以正常獲取width、height等
}
- 將一個runnable添加到Layout隊列中:View.post()
view.post(new Runnable() {
@Override
public void run() {
view.getHeight();
}
});
15. 動態修改TextView的圖片
Drawable drawable=getResources().getDrawable(R.drawable.ic_phone);
drawable.setBounds(0,0,30,35);//第一0是距左邊距離,第二0是距上邊距離,30、35分別是長寬
tv_phone.setCompoundDrawables(drawable,null,null,null);//只放左邊
setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom)
如果想手動設置大小的話就要用setCompoundDrawables,事先要給Drawable設置setBounds。
如果按照原有比例大小顯示圖片就使用setCompoundDrawablesWithIntrinsicBounds
16. 在 LinearLayout 添加分割線 divider
LinearLayout有兩個屬性
1、divider
android:divider = ""
divider可以是圖片文件,也可以是xml繪制的shape。
使用shape的時候一定要添加<size> ,一定要添加color,即使是透明也要寫上
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/black" />
<size android:height="1px" android:width="1px" />
</shape>
2、showDividers
android:showDividers = "middle|end|beginning|none"
- middle 在每一項中間添加分割線
- end 在整體的最后一項添加分割線
- beginning 在整體的最上方添加分割線
- none 無
- dividerPadding 設置間隔
17. clipToPadding
場景:常常用于paddingTop,假設內部有個屬性設置了paddingTop,但是滑動的時候paddingTop的空間無法一起滑動則使用該屬性
如設置
Android:clipToPadding=false
可以使列表的paddingTop跟隨著一起滑動。
18. 編輯框切換設置不可編輯和可編輯
/**
* 設置編輯框不可編輯
* @param editText
*/
public static void setEditTextNotEdit(EditText editText){
editText.setCursorVisible(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(false);
}
/**
* 編輯框獲取焦點
* @param editText
*/
public static void getEditFocus(EditText editText) {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.setCursorVisible(true);
editText.requestFocus();
editText.requestFocusFromTouch();
editText.setSelection(editText.getText().toString().length());
}
19. 使RecyclerView 的當前Item居中顯示
LinearSnapHelper
& PagerSnapHelper
Google 內置了兩個默認實現類,LinearSnapHelper和PagerSnapHelper。
- LinearSnapHelper: 可以使RecyclerView 的當前Item 居中顯示(橫向和豎向都支持)
- PagerSnapHelper: 使RecyclerView像ViewPager一樣的效果,每次只能滑動一頁(LinearSnapHelper支持快速滑動), PagerSnapHelper也是Item居中對齊。
20. Webview支持縮放并隱藏控制條
webSettings.setSupportZoom(true); //支持縮放
webSettings.setBuiltInZoomControls(true); //設置內置的縮放控件。
webSettings.setDisplayZoomControls(false); //隱藏原生的縮放控件`
此外檢查wap頁面的源代碼
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"/>
如果user-scalable=no,或者initial-scale和maximum-scale,minimum-scale相等,是無法縮放的。
webView設置背景圖片,如果直接給webView設置android:background是無效的,必須在Java代碼中
webView.setBackgroundColor(0);
21. EditText可以彈出安全鍵盤的方法
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
if (isShowPwd) {
// 顯示密碼
etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else{
// 隱藏密碼
etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
22. 列表中Glide加載圖片大小顯示不正常
android:adjustViewBounds="true"
adjustViewBounds只有在ImageView一邊固定,一邊為wrap_content的時候才有意義。設置為true的時候,可以讓ImageView的比例和原始圖片一樣,以達到讓圖片充滿的ImageView的效果。
23. 處理返回時關閉輸入法的同時關閉dialog
重寫EditText的onKeyPreIme方法,并設置回調來更新程序的UI
@Override
public boolean onKeyPreIme方法,并設置回調來更新程序的UI(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (listener != null) {
listener.back(this);
}
}
return false;
}
24. 代碼中動態添加radiobutton的間隔設置
設置間隔需要把setLayoutParams()放到addView之后,才有效果
RadioGroup.LayoutParams bt_params = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtil.dp2px(50,this));
bt_params.setMargins(0,ScreenUtil.dp2px(10,this),0,0);
radioGroup.addView(radioButton);
radioButton.setLayoutParams(bt_params);
25. 點擊ViewGroup時其子控件也變成pressed狀態
讓某個view自己能處理touch事件,也即設置clickable、longClickable為true;
26. 設置編輯框彈出輸入法的一種辦法
private EditText searchEdit;
searchEdit.setCursorVisible(false);
searchEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
searchEdit.setCursorVisible(true);//點擊后顯示光標,彈出輸入法
}
}
});
在他的父級設置
android:focusableInTouchMode="true"
android:focusable="true"
27. 獲取LinearLayout的寬度和高度
在調用這兩個方法之前,必須調用View.measure方法先測量組件寬度和高度
linearlayout.measure(0,0);
//獲取組件寬度
int width = linearlayout.getMeasuredWidth();
//獲取組件高度
int height = linearlayout.getMeasuredHeight();
28. NestedScrollView嵌套滑動RecycleView
mRecycleView.setNestedScrollingEnable(false);
29. AppCompat 主題中 Button 的默認 style 導致的圖片變形問題
默認 style 是"Base.Widget.AppCompat.Button"有最小寬高,具體屬性參數如下:
<style name="Base.Widget.AppCompat.Button" parent="android:Widget">
<item name="android:background">@drawable/abc_btn_default_mtrl_shape</item>
<item name="android:textAppearance">?android:attr/textAppearanceButton</item>
<item name="android:minHeight">48dip</item>
<item name="android:minWidth">88dip</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
<item name="android:gravity">center_vertical|center_horizontal</item>
</style>
解決方案
<style name="MyButton_Style" parent="Base.Widget.AppCompat.Button">
<item name="android:minHeight">0dip</item>
<item name="android:minWidth">0dip</item>
</style>
在values/styles.xml文件的AppTheme style節點中添加如下代碼:
<item name="android:buttonStyle">@style/MyButton_Style</item>
30. RadioGroup調用check(int)方法時,onCheckedChanged方法被執行兩次
改為直接根據id獲取子RadioButton對象來setChecked()
((RadioButton)mListenKindGroup.findViewById(R.id.listen_kind_group)).setChecked(true);
31. ImageView setAlpha(float)、setAlpha(int)及setImageAlpha(int)的區別
- setAlpha(float)推薦使用,取值范圍為0.0f-1.0f,透明到不透明
- setAlpha(int),已廢棄,不推薦使用,取值范圍為1-255,表示透明到不透明
- setImageAlpha(int),取值范圍1-255,表示透明到不透明
32. RelativeLayout的circular dependency問題
如果 RelativeLayout 的 height 是 wrap_content,而且它的子控件是 ALIGN_PARENT_BOTTOM,就會產生 circular dependency,導致布局鋪滿全屏。
- 解決方案:1. 動態設置布局高度 2. 替換成 LinearLayout 或其他布局。
33. EditText禁止回車鍵換行
android:inputType="text"