android適配解決方案

看了篇大神的文章,感覺用處很大,附上轉載地址

http://blog.csdn.net/lmj623565791/article/details/49990941

主要爲了解決android讓人頭疼的適配,大家可以看原文,也可以看以下內容,我會簡單記錄下用法

以前代碼一直是用dp,美工則大愛px,所以還要轉換太煩人,用這種方法佈局文件則可以用px了


首先可以建一個放這些工具代碼的包,裏面就這些類,大家可以去下載(代碼中如果出現了Object不能強轉爲int的錯誤請改爲Integer或更換高版本jdk)

http://download.csdn.net/detail/qq707548235/9364809

然後需要在主activity中加如下代碼

private static final String LAYOUT_LINEARLAYOUT = "LinearLayout";
private static final String LAYOUT_FRAMELAYOUT = "FrameLayout";
private static final String LAYOUT_RELATIVELAYOUT = "RelativeLayout";

在oncreate中加上一句話就行

AutoLayout.getInstance().auto(this);

重寫Activity的onCreateView方法

@Override
    public View onCreateView(String name, Context context, AttributeSet attrs)
    {
        View view = null;
        if (name.equals(LAYOUT_FRAMELAYOUT))
        {
            view = new AutoFrameLayout(context, attrs);
        }

        if (name.equals(LAYOUT_LINEARLAYOUT))
        {
            view = new AutoLinearLayout(context, attrs);
        }


        if (name.equals(LAYOUT_RELATIVELAYOUT))
        {
            view = new AutoRelativeLayout(context, attrs);
        }

        if (view != null) return view;

        return super.onCreateView(name, context, attrs);
    }

主方法寫這些就可以了,然後要在配置文件中加點東西,在AndroidManifest.xml的application標籤中加

<meta-data
            android:name="design_width"
            android:value="240"></meta-data>
        <meta-data
            android:name="design_height"
            android:value="320"></meta-data>

value值按需更改,和美工設計時採用的分辨率一致,比如上面的意思就是美工是按分辨率240X320的手機爲模版進行標註px的

在res/values文件加下的attrs.xml(沒有就自己建一個),裏面代碼如下

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyDownView">
        <attr name="backgroud" format="reference" />
    </declare-styleable>
<declare-styleable name="AutoLayout_Layout">
        <attr name="layout_auto_textSizeBaseWidth" format="boolean"/>
    </declare-styleable>
</resources>

做完這些就可以告一段落,我們在佈局文件中有可以安心使用px了,即使是px在不同分辨率的手機上顯示比例也是一樣的

注意:在studio中可行,eclipse可能還需要額外配置些東西,github上介紹的很詳細

https://github.com/hongyangAndroid/AndroidAutoLayout

我在手機上大概試了試,基本是沒問題(請原諒我沒多次測試,有興趣的可以各種分辨率都試試)

最後依舊是感謝大家閱讀,歡迎大神們指點。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章