前面就提到過(guò)目前手表主要分為方形,圓形兩類(lèi)的格局,并且也說(shuō)過(guò)會(huì)告訴大家通過(guò)怎么樣的方式去自動(dòng)加載對(duì)應(yīng)的布局,所以我明顯不得騙你,因?yàn)槲抑滥阕x書(shū)少。。。。
其實(shí)很簡(jiǎn)單,最開(kāi)始我以為和phone一樣通過(guò)建立不同的layout或者在代碼獲取高寬算法的方式來(lái)兼容布局,但是后面我實(shí)現(xiàn)的時(shí)候發(fā)現(xiàn),方形還好說(shuō),和手機(jī)差不多,左上角坐標(biāo)開(kāi)始計(jì)算,那圓形呢?怎么計(jì)算?我也不知道。(至少寫(xiě)到這里的時(shí)候我真的不知道,因?yàn)樽笊辖堑巾敳恐行氖莻€(gè)弧形,所以不懂怎么計(jì)算的),然后這種時(shí)候必須去找官方文檔,才發(fā)現(xiàn)原來(lái)官方已經(jīng)提供了方法(之前真是蠢哭了,一般菜鳥(niǎo)都這樣,繞圈圈,走彎路),那就是今天的主角WatchViewStub。
之前我們布局就是直接在主activity引用對(duì)應(yīng)的布局,引用控件,實(shí)現(xiàn)邏輯就可以了,所以既然是兼容模式,肯定不能這么玩滴。
首先在layout下建立一個(gè)叫activity_wear.xml布局文件內(nèi)容如下:
<android.support.wearable.view.WatchViewStub
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/watch_view_stub"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:rectLayout="@layout/rect_activity_wear"
app:roundLayout="@layout/round_activity_wear">
</android.support.wearable.view.WatchViewStub>```
通過(guò)上面的代碼可以看出有兩個(gè)屬性:
1.app:rectLayout="@layout/rect_activity_wear"
矩形(方形)格局的布局文件
2.app:roundLayout="@layout/round_activity_wear"
圓形格局的布局文件
布局文件做好以后,就在需要引用的activity中setContent布局就可以了
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wear);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override public void onLayoutInflated(WatchViewStub stub) {
// Now you can access your views
TextView tv = (TextView) stub.findViewById(R.id.text);
...
}
});
}
布局加載完成后系統(tǒng)根據(jù)當(dāng)前手表的格局加載對(duì)應(yīng)的文件,等待布局加載完成直接就可以在onLayoutInflated中實(shí)現(xiàn)你的相應(yīng)邏輯。

-------------------------華麗麗的分割線---------------------------------
總結(jié):因?yàn)槟壳笆袌?chǎng)上的手表還沒(méi)有很多的樣式,主要就是這兩種模式,所以在適配方面應(yīng)該不是很難,根據(jù)不同的格局分別做不同的布局
,感覺(jué)也挺方便的。
<a href="http://www.lxweimin.com/p/6141678a58a1">下一篇</a>