LoginSignup
21
24

More than 5 years have passed since last update.

タブアイテムにbadgeを取り付ける方法

Posted at

Githubに上げられているandroid-viewbadgerのjarファイルを活用すればいとも簡単にバッジを取り付けることが出来ます。

Github参考URL
https://github.com/jgilfelt/android-viewbadger

しかし、アイコンとオーバーラップするバッジの表示位置設定されていなかったことや、バッジの色の指定が出来なかったこと、また4つ以上のタブを作った時に横幅が足りなくなって潰れてしまうことがあったことなどで、個人的にはバッジを作って取り付ける方が柔軟性が高いように感じました。

バッジを自分で作ってみる

そこで、自分でバッジを作成してみます。

res/drawbable/
badge.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval" >

    <stroke android:width="2dp" android:color="#3cb371" />

    <corners android:radius="10dp"/>

    <padding android:left="2dp" />

    <solid android:color="#3cb371"/>

</shape>

res/layout/
tabbadge.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dip" 
    android:layout_height="64dip"
    android:layout_weight="1" 
    android:layout_marginLeft="-3dip" 
    android:layout_marginRight="-3dip" 
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/chat_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/tabicon"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/chat_icon"
        android:layout_toRightOf="@+id/chat_icon"
        android:layout_marginLeft="-8dp"
        android:layout_marginTop="0dp"
        android:paddingTop="2dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="2dp"
        android:textSize="8sp"
        android:textStyle="bold"
        android:textColor="#ffffff"
        android:background="@drawable/badge"
        />
</RelativeLayout>

badge.xmlはTextViewとしてImageViewの上に配置します。(RelativeLayoutなので自分で細かい位置を設定する)ここで指定したImageViewはタブアイコンとなります。

次にjavaファイルのonCreate内を見てみます

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View chatTab1 = inflater.inflate(R.layout.tabbadge, null);
        TextView tv1 = (TextView) chatTab1.findViewById(R.id.tv1);

まずLayoutInflaterでtabbadge.xmlのビューを作成しました。setContentViewではそのクラスの元になるview,このlayoutInflaterはあくまでもバッジの作成のみに使用されています。
TabSpec firstTab = tabHost.newTabSpec("First").setIndicator(chatTab1)
                .setContent(R.id.first_content);
        tabHost.addTab(firstTab);

タブを作った後はsetIndicatorの中に上で定義したchatTab1を入れてあげれば完成。

こうすることでバッジの色や位置を自由に指定することが可能になり、タブの数が4、5個あっても大きさと場所さえ上手く調整すれば綺麗に表示されるようになります。

バッジの作り方参考URL
http://stackoverflow.com/questions/6394768/adding-badge-to-tab-in-android

21
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
24