dp、sp和px
- px:像素,不同設(shè)備不同的顯示屏顯示效果是相同的
- dp:與“像素密度”密切相關(guān)。
什么是像素密度?假設(shè)有一部手機,屏幕的物理尺寸為1.5英寸x2英寸,屏幕分辨率為240x320,則我們可以計算出在這部手機的屏幕上,每英寸包含的像素點的數(shù)量為240/1.5=160dpi(橫向)或320/2=160dpi(縱向),160dpi就是這部手機的像素密度,像素密度的單位dpi是Dots Per Inch的縮寫,即每英寸像素數(shù)量。
不同的手機/平板可能具有不同的像素密度。使用dp可以讓圖片在不同像素密度手機上顯示出來的效果十分接近。
dp = (px / 1.5 + 0.5)
- dip = dp
- sp:主要用于字體顯示,顯示字體隨系統(tǒng)設(shè)置改變而改變
這些單位何時使用?
- 文字尺寸一律用sp
-非文字尺寸一律用dp
-偶爾需要px,例如需要在屏幕上畫一條細的分割線
Inflater
LayoutInflater: 用于將一個XML布局文件實例化到對應(yīng)的view。
獲得LayoutInflater的三種方式:
LayoutInflater inflater = getLayoutInflater();//在Activity中調(diào)用
LayoutInflater inflater = LayoutInflater.from(context)
getSystemService(Context.LAYOUT_INFLATER_SERVICE)```
將一個XML布局文件實例化到對應(yīng)的view:
```View v = inflater.inflate(R.layout.custom, null);//第二個參數(shù)為ViewGroup```
獲取界面中的組件:```view.findViewById();```
###提取布局屬性:theme & style
- Theme是針對窗體級別的,改變窗體樣式
- Style是針對窗體元素級別的,改變指定控件或者Layout
style中的parent屬性表明此style會繼承parent style的所有內(nèi)容
<resource>
<style name="CustomTextView">
<item name="android:background">@color/red</item> 表示其中的一個屬性
<item name="android:textSize">20sp</item>
</style>
<style name="DIYTextView" parent="CustomTextView">
</style>
</resource>
```<TextView style="@style/CustomTextView"/>```
使用setTheme方法可以動態(tài)切換主題。
關(guān)于自定義主題樣式更多內(nèi)容可參考[zziss](http://www.cnblogs.com/zziss/archive/2012/03/17/2403251.html)
###View是如何工作的
Android程序中的任何一個布局、任何一個控件其實都是直接或間接繼承自View的,比如TextView, Button, ListView等等。這些視圖想要顯示在屏幕上,都必須要經(jīng)過非常科學(xué)的繪制流程后才能顯示出來。
**每個視圖的繪制都必須要經(jīng)過三個階段:**
- Measure
這個階段View會做一次測量,算出自己需要占用多大的面積。
```protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {}```
onMeasure方法的兩個參數(shù)分別用于確定視圖的高度和寬度的規(guī)格和大小。
- Layout
給視圖進行布局,確定視圖的位置。
```protected void onLayout(boolean changed, int left, int top, int right, int bottom) {}```
- Draw
進行視圖繪制。
```protected void onDraw(Canvas canvas) {}```
當(dāng)視圖改變時,需要調(diào)用 **invalidate()** 方法使改變顯示。
**創(chuàng)建自定義控件的形式:**
- 繼承已有的控件來實現(xiàn)自定義控件
例如Button就是繼承于TextView的
- 繼承一個布局文件來實現(xiàn)自定義控件
- 基層view類來實現(xiàn)自定義控件
下面是一個簡單的例子<br>- 實現(xiàn)一個圓形的黑色按鈕<br>- 中間有一個白色的數(shù)字<br>- 數(shù)字起始為0<br>- 每點擊一次增加1<br>- 當(dāng)達到上限時提示目標達成<br>- 按鈕下有個文本框可以設(shè)置目標
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); //默認值為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);
//第二、三個參數(shù)為繪制文本參考的x,y基準線位置
}
@Override
public void onClick(View view) {
if (mButtonNum == mTarget) {
mButtonNum = 0;
Toast.makeText(mContext, "目標已達成", Toast.LENGTH_SHORT).show();
}
else {
mButtonNum++;
}
mText = String.valueOf(mButtonNum);
invalidate();
}
public void setTarget(int num) {
mTarget = num;
}
}
首先定義一個CircleCountButton類繼承自View
<resources>
<declare-styleable name="DIYbtn">
<attr name="target" format="integer"/>
<attr name="btnTextSize" format="dimension"/>
</declare-styleable>
</resources>
編寫values/attrs.xml,在其中編寫styleable標簽元素。
代碼中聲明了自定義視圖的兩個屬性target和btnTextSize。
format為屬性的類型。
mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.DIYbtn);
mTarget = mTypedArray.getInteger(R.styleable.DIYbtn_target, 10); //默認值為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>
