Android + 在LinearLayout上使用setDividerDrawable方法?

6

我希望能够动态地向LinearLayout的子元素添加分隔符。我在文档中看到LinearLayout包含一个常量“SHOW_DIVIDER_MIDDLE”,以及获取和设置分隔符的方法。有人能告诉我如何实现吗?谢谢!

“这个不起作用”

布局xml:

<LinearLayout android:id="@+id/bar"
        android:orientation="horizontal" 
        android:layout_height="40dip" android:layout_width="fill_parent"
        android:background="@drawable/ab_background_gradient" android:gravity="right|center_vertical">

        <!-- sort button -->
        <Button android:id="@+id/sortBtn" android:background="@drawable/defaultt"
                android:layout_width="30dip" android:layout_height="30dip" android:onClick="sortThis" />

        <!-- add button -->
        <Button android:id="@+id/addBtn" android:background="@drawable/defaultt"
                android:layout_width="30dip" android:layout_height="30dip" android:onClick="addThis" />
    </LinearLayout>

主函数:

...
private void setupViews() {
        //bar
        mBar = (LinearLayout) findViewById(R.id.bar);
        mBar.setDividerDrawable(R.drawable.divider);
}
1个回答

7
您需要将从R.drawable.divider得到的资源ID转换为一个Drawable对象,例如:
import android.content.res.Resources;
...

public void onCreate(Bundle savedInstanceState) {
    ...

    Resources res = this.getResources();

    LinearLayout layout = new LinearLayout(this);
    layout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE | LinearLayout.SHOW_DIVIDER_BEGINNING | LinearLayout.SHOW_DIVIDER_END);
    layout.setDividerDrawable(res.getDrawable(R.drawable.divider));

    ...
 }
...

这假设你的资源目录中有一个名为'divider.jpg'(或类似)的文件。

3
这可以运行,但请注意,setShowDividers是在API级别11(蜂巢)中添加的。 http://stackoverflow.com/questions/8304221/nosuchmethod-exception-for-setshowdividers - worked
@worked 你可以使用ActionBarSherlock中的IcsLinearLayout,但请注意它并不是用来使用的。还有一个在support库中的LinearLayoutICS。 - android developer
Xamarin开发者使用这个_tabLayout.SetDividerDrawable(Resources.GetDrawable(Resource.Drawable.divider)); - Sumit Pathak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接