Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/216.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android TextView上的图形背景(非全宽)_Android_Textview_Android Custom View_Compound Drawables - Fatal编程技术网

Android TextView上的图形背景(非全宽)

Android TextView上的图形背景(非全宽),android,textview,android-custom-view,compound-drawables,Android,Textview,Android Custom View,Compound Drawables,我想在TextView上设置背景可绘制(或资源),而不考虑其复合可绘制宽度(和填充) 获取复合物的宽度(更精确地说是左一个)及其填充物应该不是问题,但是textview宽度上的背景设置减去复合物可绘制的宽度(如上所述) 如果你对此有什么建议,请告诉我 以下是所需的结果: 注:我曾考虑过使用水平线性布局,将ImageView和TextView作为其子对象,并仅在TextView上设置背景,但我感兴趣的是,如果可能的话,使用更少的视图(在本例中,正好是一个视图)获得相同的结果。您可以使用支持插入的

我想在TextView上设置背景可绘制(或资源),而不考虑其复合可绘制宽度(和填充)

获取复合物的宽度(更精确地说是左一个)及其填充物应该不是问题,但是textview宽度上的背景设置减去复合物可绘制的宽度(如上所述)

如果你对此有什么建议,请告诉我

以下是所需的结果:

注:我曾考虑过使用水平线性布局,将ImageView和TextView作为其子对象,并仅在TextView上设置背景,但我感兴趣的是,如果可能的话,使用更少的视图(在本例中,正好是一个视图)获得相同的结果。

您可以使用支持插入的布局,例如:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:left="dimension" android:right="dimension">
        <shape android:shape="rectangle">
            <solid android:color="color" />
        </shape>
    </item>
</layer-list>
要根据左侧CompoundDrawable设置左侧填充,可以执行以下操作:

private void setBackground(TextView textView, DividerDrawable background) {
    Drawable drawableLeft = textView.getCompoundDrawables()[0];
    int paddingLeft = drawableLeft != null ?
            textView.getPaddingLeft() + drawableLeft.getIntrinsicWidth() + textView.getCompoundDrawablePadding() :
            textView.getPaddingLeft();
    background.setPaddingLeft(paddingLeft);
    textView.setBackground(background);
}
要充分利用这一切,请这样称呼它:

    DividerDrawable dividerDrawable = new DividerDrawable(this);
    TextView textView = (TextView) findViewById(R.id.text);
    setBackground(textView, dividerDrawable);

谢谢在你的帮助下我成功了。我想再问你一件事:是否有一个方法,每当我在TextView(包括从xml)上设置(或更改其位置)一个drawable时都会被调用。ie:setCompoundDrawables/setCompoundDrawablesRelative,还是我需要覆盖每一个,并计算新的宽度和填充?对不起,我不太明白你的意思。如果调用setCompoundDrawables(),将调用requestLayout()来处理更改(测量、布局和绘图)。你想达到什么目的?我的意思是,在哪里是将左插图添加到layerdrawable的最佳位置,这样每当左插图可见/消失或放置在其他地方时,它就会自动改变自己?正如我在问题中试图解释的那样,我需要灰色线不显示在图标上,而只显示在文本上。你可以为每个状态创建一个可绘制的,并在这些状态之间切换,甚至可以编写你自己的可绘制类。我通过设置一个带有左填充的可绘制层列表的背景来实现。我感兴趣的是动态地设置图层列表的左填充(每当我在TextView上设置左填充或左填充时,背景(视图顶部的分隔符)应该相应地缩小其宽度。你能帮我吗?TextView中的背景在哪里(在需要的结果中)?@shryansjain位于文本视图的顶部或底部(图片中的分隔符),无论哪种方式都有效。
    DividerDrawable dividerDrawable = new DividerDrawable(this);
    TextView textView = (TextView) findViewById(R.id.text);
    setBackground(textView, dividerDrawable);