2016-01-20 73 views
2

我發現瞭如何設置customView的以下文檔。但是,當我將佈局中的id更改爲「text1」和「圖標」時,setText()setIcon()不起作用。如何使用android.support.design.widget.TabLayout來創建標籤的自定義佈局?

公共TabLayout.Tab setCustomView(INT layoutResId)

設置自定義視圖要用於該選項卡。

如果充氣佈局包含ID爲text1TextView,那麼將使用setText(CharSequence)給出的值進行更新。同樣,如果此佈局包含帶有ID圖標的ImageView,則它將使用給予setIcon(Drawable)的值進行更新。

(來源:http://developer.android.com/reference/android/support/design/widget/TabLayout.Tab.html#setCustomView(int)

誰能給我這是如何工作的例子嗎?

Java代碼:

TabLayout.Tab tabAdd = tabLayout.getTabAt(0); 
    tabAdd.setCustomView(R.layout.tab_layout_custom_view); 
    tabAdd.setText("Add"); 
    tabAdd.setIcon(R.mipmap.add_tab).setText("Add"); 

佈局代碼:

<ImageView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" 
    android:id="@+id/icon"/> 
<TextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="0" 
    android:id="@+id/text1" 
    android:gravity="center" 
    android:layout_below="@+id/icon" /> 
+1

值得一讀。 [Android中'@ + id','@ id'和'@ android'之間的區別](http://android-wtf.com/2012/11/difference-between-at-plus-id-and-at- id-in-android /) –

+0

您可以選擇使自己管理的自定義視圖充滿膨脹,在這裏查看完整的實現:http://stackoverflow.com/a/32547335/4409409 –

回答

4

您需要使用系統資源標識符。即,@android:id/text1@android:id/icon

<ImageView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" 
    android:id="@android:id/icon"/> 
<TextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="0" 
    android:id="@android:id/text1" 
    android:gravity="center" 
    android:layout_below="@android:id/icon" /> 

如果您需要在您的代碼來引用這些ID,他們將android.R.id.text1android.R.id.icon

+1

我在這裏找到了更多的信息,對於任何有興趣的人。 http://developer.android.com/guide/topics/ui/declaring-layout.html#id – ddsnowboard

+1

謝謝!這樣可行 –