1. 用代碼設(shè)置ImageView的src和background
設(shè)置ImageView的src:
setImageDrawable(Drawable drawable);
setImageBitmap(Bitmap bm);
setImageResource(int resId);
代碼設(shè)置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中保存不帶單位的數(shù)值
要在dimens.xml中保存不帶單位的數(shù)值,可以用如下格式來定義森篷。
<item name="text_line_spacing" type="dimen" format="float">1.2</item>
在上述定義中抖僵,type=”dimen”屬性表示定義的item的資源類型是dimen類型缭保。除了可以使用”dimen”外,還可以使用color击喂,string,style等類型,但由于其他類型都可以直接定義匕荸,且沒有數(shù)值的約束,所以一般不需要通過這種方法來定義枷邪。format=”float”屬性表示定義的數(shù)值類型是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設(shè)置
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
- 文字動(dòng)態(tài)設(shè)置的話需要超出一行
- 在當(dāng)前控件是visible的情況下textView.setSelected(true);
4. Android自定義Dialog設(shè)置有蒙版半透明背景的方法
<item name="android:backgroundDimEnabled">true</item>
<item name="android:backgroundDimAmount">0.42</item>
5. ScrollView中嵌套WebView時(shí)的焦點(diǎn)問題(ListView的item焦點(diǎn)搶奪同理)
外層使用ScroolView侦铜,內(nèi)層嵌套使用WebView,每次進(jìn)入Activity頁面時(shí)钟鸵,整個(gè)頁面起始位置并不是頂部钉稍,這是因?yàn)閃ebView加載后獲得焦點(diǎn)導(dǎo)致的(ListView也會(huì)出現(xiàn)類似問題,即使修正了高度携添,也會(huì)主動(dòng)獲得焦點(diǎn)嫁盲,使得屏幕產(chǎn)生錯(cuò)誤的滾動(dòng))
通過設(shè)置ScrollView包含的第一個(gè)viewgroup的
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants" >
viewgroup會(huì)覆蓋子類控件而直接獲得焦點(diǎn)來輕松解決問題。
6. 設(shè)置按鈕不可點(diǎn)擊
button.setEnabled(false);
或者
button.setClickable(false);
- 注意:
setClickable(false)方法一定要在setOnClickListener()方法之后用;
因?yàn)閟etOnClickListener()方法會(huì)重新繪制View;
7. 編輯框光標(biāo)保持光標(biāo)位于內(nèi)容最后
setText之后設(shè)置:
etView.requestFocus();
否則先獲得了焦點(diǎn)烈掠,后續(xù)再設(shè)置內(nèi)容羞秤,此時(shí)焦點(diǎn)肯定是放在內(nèi)容之前的了,則就需要額外調(diào)用setSelection去調(diào)整位置了
etView.setSelection(etView.getText().toString().length());
8. ImageView擴(kuò)大點(diǎn)擊區(qū)域
ImageView 直接設(shè)置其padding值達(dá)到目的,或者
android:scaleType="centerInside"
android:src="@drawable/ic_edit"
此時(shí)可以直接設(shè)置控件寬高來控制大小左敌,注意不能用background瘾蛋,這會(huì)導(dǎo)致圖片變形
9. 禁止EditText自動(dòng)獲取焦點(diǎn)
android:focusable="true"
android:focusableInTouchMode="true"
設(shè)置光標(biāo)不可見
cursorVisible
10. TextView的文字也可以設(shè)置按下效果
新建 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. 一個(gè)控件設(shè)置TextView和兩個(gè)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. 監(jiān)聽ViewFlipper滑動(dòng)的子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() { //從繼承關(guān)系中發(fā)現(xiàn)當(dāng)子view變化的時(shí)候會(huì)調(diào)用該方法,因此在這里弄個(gè)回調(diào)
super.showNext();
mOnViewCountListener.viewCount(getDisplayedChild());
}
private OnViewCountListener mOnViewCountListener;
public void setOnViewCountListener(OnViewCountListener mOnViewCountListener)
{
this.mOnViewCountListener=mOnViewCountListener;
}
public interface OnViewCountListener{
void viewCount(int count);
}
}
13. 官方提供的自動(dòng)改變文本大小的TextView
在XML中設(shè)置
<?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" // 設(shè)置TextView大小設(shè)置樣式為支持改變(none時(shí)為不支持改變)
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>
在代碼中動(dòng)態(tài)設(shè)置
<?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>
在代碼中進(jìn)行改變字號(hào)的設(shè)置
TextViewCompat.setAutoSizeTextTypeWithDefaults(
textView, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(
textView, 8, 25, 1, TypedValue.COMPLEX_UNIT_SP);
- 控件的寬度和高度必須要有具體的值矫限,不能設(shè)置為wrap_content
- 單行顯示需要使用maxLines="1"
14. 獲取控件寬高建議使用的方法
- 重寫Activity的onWindowFocusChanged方法,在該方法中獲取
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
//此處可以正常獲取width哺哼、height等
}
- 將一個(gè)runnable添加到Layout隊(duì)列中:View.post()
view.post(new Runnable() {
@Override
public void run() {
view.getHeight();
}
});
15. 動(dòng)態(tài)修改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)
如果想手動(dòng)設(shè)置大小的話就要用setCompoundDrawables,事先要給Drawable設(shè)置setBounds无宿。
如果按照原有比例大小顯示圖片就使用setCompoundDrawablesWithIntrinsicBounds
16. 在 LinearLayout 添加分割線 divider
LinearLayout有兩個(gè)屬性
1茵汰、divider
android:divider = ""
divider可以是圖片文件,也可以是xml繪制的shape孽鸡。
使用shape的時(shí)候一定要添加<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 在每一項(xiàng)中間添加分割線
- end 在整體的最后一項(xiàng)添加分割線
- beginning 在整體的最上方添加分割線
- none 無
- dividerPadding 設(shè)置間隔
17. clipToPadding
場景:常常用于paddingTop豆胸,假設(shè)內(nèi)部有個(gè)屬性設(shè)置了paddingTop,但是滑動(dòng)的時(shí)候paddingTop的空間無法一起滑動(dòng)則使用該屬性
如設(shè)置
Android:clipToPadding=false
可以使列表的paddingTop跟隨著一起滑動(dòng)奥洼。
18. 編輯框切換設(shè)置不可編輯和可編輯
/**
* 設(shè)置編輯框不可編輯
* @param editText
*/
public static void setEditTextNotEdit(EditText editText){
editText.setCursorVisible(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(false);
}
/**
* 編輯框獲取焦點(diǎn)
* @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 的當(dāng)前Item居中顯示
LinearSnapHelper
& PagerSnapHelper
Google 內(nèi)置了兩個(gè)默認(rèn)實(shí)現(xiàn)類,LinearSnapHelper和PagerSnapHelper晚胡。
- LinearSnapHelper: 可以使RecyclerView 的當(dāng)前Item 居中顯示(橫向和豎向都支持)
- PagerSnapHelper: 使RecyclerView像ViewPager一樣的效果灵奖,每次只能滑動(dòng)一頁(LinearSnapHelper支持快速滑動(dòng)), PagerSnapHelper也是Item居中對(duì)齊。
20. Webview支持縮放并隱藏控制條
webSettings.setSupportZoom(true); //支持縮放
webSettings.setBuiltInZoomControls(true); //設(shè)置內(nèi)置的縮放控件估盘。
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設(shè)置背景圖片爆阶,如果直接給webView設(shè)置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的時(shí)候才有意義辨图。設(shè)置為true的時(shí)候班套,可以讓ImageView的比例和原始圖片一樣,以達(dá)到讓圖片充滿的ImageView的效果故河。
23. 處理返回時(shí)關(guān)閉輸入法的同時(shí)關(guān)閉dialog
重寫EditText的onKeyPreIme方法吱韭,并設(shè)置回調(diào)來更新程序的UI
@Override
public boolean onKeyPreIme方法,并設(shè)置回調(diào)來更新程序的UI(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (listener != null) {
listener.back(this);
}
}
return false;
}
24. 代碼中動(dòng)態(tài)添加radiobutton的間隔設(shè)置
設(shè)置間隔需要把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. 點(diǎn)擊ViewGroup時(shí)其子控件也變成pressed狀態(tài)
讓某個(gè)view自己能處理touch事件理盆,也即設(shè)置clickable、longClickable為true凑阶;
26. 設(shè)置編輯框彈出輸入法的一種辦法
private EditText searchEdit;
searchEdit.setCursorVisible(false);
searchEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
searchEdit.setCursorVisible(true);//點(diǎn)擊后顯示光標(biāo)猿规,彈出輸入法
}
}
});
在他的父級(jí)設(shè)置
android:focusableInTouchMode="true"
android:focusable="true"
27. 獲取LinearLayout的寬度和高度
在調(diào)用這兩個(gè)方法之前,必須調(diào)用View.measure方法先測量組件寬度和高度
linearlayout.measure(0,0);
//獲取組件寬度
int width = linearlayout.getMeasuredWidth();
//獲取組件高度
int height = linearlayout.getMeasuredHeight();
28. NestedScrollView嵌套滑動(dòng)RecycleView
mRecycleView.setNestedScrollingEnable(false);
29. AppCompat 主題中 Button 的默認(rèn) style 導(dǎo)致的圖片變形問題
默認(rèn) style 是"Base.Widget.AppCompat.Button"有最小寬高宙橱,具體屬性參數(shù)如下:
<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節(jié)點(diǎn)中添加如下代碼:
<item name="android:buttonStyle">@style/MyButton_Style</item>
30. RadioGroup調(diào)用check(int)方法時(shí)姨俩,onCheckedChanged方法被執(zhí)行兩次
改為直接根據(jù)id獲取子RadioButton對(duì)象來setChecked()
((RadioButton)mListenKindGroup.findViewById(R.id.listen_kind_group)).setChecked(true);
31. ImageView setAlpha(float)、setAlpha(int)及setImageAlpha(int)的區(qū)別
- 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,就會(huì)產(chǎn)生 circular dependency的烁,導(dǎo)致布局鋪滿全屏褐耳。
- 解決方案:1. 動(dòng)態(tài)設(shè)置布局高度 2. 替換成 LinearLayout 或其他布局。
33. EditText禁止回車鍵換行
android:inputType="text"