dp冈绊、sp和px
- px:像素家淤,不同設(shè)備不同的顯示屏顯示效果是相同的
- dp:與“像素密度”密切相關(guān)。
什么是像素密度愚屁?假設(shè)有一部手機(jī)济竹,屏幕的物理尺寸為1.5英寸x2英寸,屏幕分辨率為240x320霎槐,則我們可以計(jì)算出在這部手機(jī)的屏幕上送浊,每英寸包含的像素點(diǎn)的數(shù)量為240/1.5=160dpi(橫向)或320/2=160dpi(縱向),160dpi就是這部手機(jī)的像素密度丘跌,像素密度的單位dpi是Dots Per Inch的縮寫袭景,即每英寸像素?cái)?shù)量。
不同的手機(jī)/平板可能具有不同的像素密度闭树。使用dp可以讓圖片在不同像素密度手機(jī)上顯示出來的效果十分接近耸棒。
dp = (px / 1.5 + 0.5)
- dip = dp
- sp:主要用于字體顯示,顯示字體隨系統(tǒng)設(shè)置改變而改變
這些單位何時(shí)使用报辱?
- 文字尺寸一律用sp
-非文字尺寸一律用dp
-偶爾需要px,例如需要在屏幕上畫一條細(xì)的分割線
Inflater
LayoutInflater: 用于將一個(gè)XML布局文件實(shí)例化到對(duì)應(yīng)的view与殃。
獲得LayoutInflater的三種方式:
LayoutInflater inflater = getLayoutInflater();//在Activity中調(diào)用
LayoutInflater inflater = LayoutInflater.from(context)
getSystemService(Context.LAYOUT_INFLATER_SERVICE)```
將一個(gè)XML布局文件實(shí)例化到對(duì)應(yīng)的view:
```View v = inflater.inflate(R.layout.custom, null);//第二個(gè)參數(shù)為ViewGroup```
獲取界面中的組件:```view.findViewById();```
###提取布局屬性:theme & style
- Theme是針對(duì)窗體級(jí)別的,改變窗體樣式
- Style是針對(duì)窗體元素級(jí)別的,改變指定控件或者Layout
style中的parent屬性表明此style會(huì)繼承parent style的所有內(nèi)容
<resource>
<style name="CustomTextView">
<item name="android:background">@color/red</item> 表示其中的一個(gè)屬性
<item name="android:textSize">20sp</item>
</style>
<style name="DIYTextView" parent="CustomTextView">
</style>
</resource>
```<TextView style="@style/CustomTextView"/>```
使用setTheme方法可以動(dòng)態(tài)切換主題幅疼。
關(guān)于自定義主題樣式更多內(nèi)容可參考[zziss](http://www.cnblogs.com/zziss/archive/2012/03/17/2403251.html)
###View是如何工作的
Android程序中的任何一個(gè)布局米奸、任何一個(gè)控件其實(shí)都是直接或間接繼承自View的,比如TextView, Button, ListView等等爽篷。這些視圖想要顯示在屏幕上悴晰,都必須要經(jīng)過非常科學(xué)的繪制流程后才能顯示出來逐工。
**每個(gè)視圖的繪制都必須要經(jīng)過三個(gè)階段:**
- Measure
這個(gè)階段View會(huì)做一次測量铡溪,算出自己需要占用多大的面積。
```protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {}```
onMeasure方法的兩個(gè)參數(shù)分別用于確定視圖的高度和寬度的規(guī)格和大小钻弄。
- Layout
給視圖進(jìn)行布局佃却,確定視圖的位置。
```protected void onLayout(boolean changed, int left, int top, int right, int bottom) {}```
- Draw
進(jìn)行視圖繪制窘俺。
```protected void onDraw(Canvas canvas) {}```
當(dāng)視圖改變時(shí)饲帅,需要調(diào)用 **invalidate()** 方法使改變顯示。
**創(chuàng)建自定義控件的形式:**
- 繼承已有的控件來實(shí)現(xiàn)自定義控件
例如Button就是繼承于TextView的
- 繼承一個(gè)布局文件來實(shí)現(xiàn)自定義控件
- 基層view類來實(shí)現(xiàn)自定義控件
下面是一個(gè)簡單的例子<br>- 實(shí)現(xiàn)一個(gè)圓形的黑色按鈕<br>- 中間有一個(gè)白色的數(shù)字<br>- 數(shù)字起始為0<br>- 每點(diǎn)擊一次增加1<br>- 當(dāng)達(dá)到上限時(shí)提示目標(biāo)達(dá)成<br>- 按鈕下有個(gè)文本框可以設(shè)置目標(biāo)
public class CircleCountButton extends View implements View.OnClickListener {
private Paint mPaint;
private float mTextSize;
private int mButtonNum;
private String mText;
private Rect mRect;
private int mTarget;
private TypedArray mTypedArray;
private Context mContext;
public CircleCountButton(Context context) {
this(context, null);
}
public CircleCountButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleCountButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs){
mContext = context;
mPaint = new Paint();
mButtonNum = 0;
mText = String.valueOf(mButtonNum);
mRect = new Rect();
mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.DIYbtn);
mTarget = mTypedArray.getInteger(R.styleable.DIYbtn_target, 10); //默認(rèn)值為20
mTextSize = mTypedArray.getDimension(R.styleable.DIYbtn_btnTextSize, 100);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//設(shè)定按鈕背景顏色為黑色
mPaint.setColor(Color.BLACK);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, mPaint);
//設(shè)定文字顏色為白色
mPaint.setColor(Color.WHITE);
//設(shè)定字體大小
mPaint.setTextSize(mTextSize);
//返回文字的邊界到Rect
mPaint.getTextBounds(mText, 0, mText.length(), mRect);
canvas.drawText(mText, getWidth() / 2 - mRect.width() / 2,
getHeight() / 2 + mRect.height() / 2, mPaint);
//第二瘤泪、三個(gè)參數(shù)為繪制文本參考的x,y基準(zhǔn)線位置
}
@Override
public void onClick(View view) {
if (mButtonNum == mTarget) {
mButtonNum = 0;
Toast.makeText(mContext, "目標(biāo)已達(dá)成", Toast.LENGTH_SHORT).show();
}
else {
mButtonNum++;
}
mText = String.valueOf(mButtonNum);
invalidate();
}
public void setTarget(int num) {
mTarget = num;
}
}
首先定義一個(gè)CircleCountButton類繼承自View
<resources>
<declare-styleable name="DIYbtn">
<attr name="target" format="integer"/>
<attr name="btnTextSize" format="dimension"/>
</declare-styleable>
</resources>
編寫values/attrs.xml灶泵,在其中編寫styleable標(biāo)簽元素。
代碼中聲明了自定義視圖的兩個(gè)屬性target和btnTextSize对途。
format為屬性的類型赦邻。
mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.DIYbtn);
mTarget = mTypedArray.getInteger(R.styleable.DIYbtn_target, 10); //默認(rèn)值為20
mTextSize = mTypedArray.getDimension(R.styleable.DIYbtn_btnTextSize, 100);
在自定義視圖類中通過**TypedArray**獲取屬性
<com.kevinwang.diybutton.CircleCountButton
android:layout_width="100dp"
android:layout_height="100dp"
app:target="10"
app:btnTextSize="25sp"
android:id="@+id/count_btn"
android:layout_centerHorizontal="true"
/>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
......
/>
</RelativaLayout>
在布局文件中使用屬性,注意想要使用自定義屬性实檀,應(yīng)該注意nameSpace.
public class MainActivity extends AppCompatActivity {
private CircleCountButton mCircleCountButton;
private EditText mEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCircleCountButton = (CircleCountButton) findViewById(R.id.count_btn);
mCircleCountButton.setOnClickListener(mCircleCountButton);
mEditText = (EditText) findViewById(R.id.target_text);
View.OnKeyListener onKeyListener = new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_ENTER) {//i為keycode
mCircleCountButton.setTarget(Integer.
valueOf(mEditText.getText().toString()));
InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager.isActive()) {
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
return false;
}
};
mEditText.setOnKeyListener(onKeyListener);
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kevinwang.diybutton.MainActivity">
<com.kevinwang.diybutton.CircleCountButton
android:layout_width="100dp"
android:layout_height="100dp"
app:target="10"
app:btnTextSize="25sp"
android:id="@+id/count_btn"
android:layout_centerHorizontal="true"
/>
<EditText
android:id="@+id/target_text"
android:layout_below="@id/count_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="@string/target_hint"
android:inputType="number"/>
</RelativeLayout>
