Эффект рисования Ripple искажается при применении к фону 9patch - PullRequest
0 голосов
/ 05 октября 2018

У меня есть 9 патчей, которые я хочу использовать в качестве фона для вида.Я хочу, чтобы представление показывало волновой эффект, который следует контуру патча 9 при нажатии на представление.Вот мои действия, макет и код для рисования.

MainActivity.kt:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val click = findViewById<ConstraintLayout>(R.id.container)
        click.setOnClickListener { Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show() }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.antonc.testapp.MainActivity">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="8dp"
        android:paddingStart="8dp"
        android:paddingEnd="8dp"
        android:paddingTop="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:background="@drawable/tooltip_background"
        android:backgroundTint="#2681d8"
        tools:layout_editor_absoluteX="8dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello test test !!!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            />

    </android.support.constraint.ConstraintLayout>

</android.support.constraint.ConstraintLayout>

tooltip_background.xml:

<?xml version="1.0" encoding="utf-8"?>
    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#33000000">
    <item android:drawable="@drawable/tooltip_left_top"/>
    <item android:id="@android:id/mask" android:drawable="@drawable/tooltip_left_top"/>
</ripple>

tooltip_left_top.9.png:

tooltip_left_top.9.png

Но когда я нажимаю на него, рисование пульсации сильно искажается, как будто оно растянутона размер вида без соблюдения правил растяжения 9 патч.Как настроить пульсации так, чтобы они были такими же, как фон?

1020 *Result

Ответы [ 2 ]

0 голосов
/ 10 октября 2018

Обновление: Я переработал ответ, чтобы уточнить проблему.Следующее было отредактировано, чтобы отразить изменения:

TL; DR Не используйте android:backgroundTint для фоновых рисунков, основанных на рисовании из девяти пятен, по крайней мере для API 28. Установите оттенок вcode.


Эта проблема имеет отношение что-то к фоновому оттенку.Я объясню, как я пришел к такому выводу, обратившись к следующему видео.

enter image description here

Я буду ссылаться на пузыри как от view1 до view4 сверху внизниз.Я изменил ваш девятый патч, чтобы лучше видеть патчи, поскольку ваш девятый патч был в основном черным.

View1, когда щелчок, показывает соответствующий эффект ряби.Он имеет волнистый фон, но без оттенка фона.

View2 - это то, что вы видите на своем фоне - оно просто испорчено.Для этого вида задан фоновый оттенок в XML.

Высота view3 была установлена ​​на высоту view1, чтобы увидеть, как выглядит рябь.Как вы можете видеть, пульсация выглядит правильно для высоты.Это искаженное фоновое изображение без пульсаций.

View4 - то же самое, что и view2, за исключением того, что для него добавлен программный оттенок RippleDrawable.Как вы можете видеть, этот вид выглядит и ведет себя как следует.

Итог?Не устанавливайте фоновый оттенок для «девяти патчей» в XML.Установите это в коде.Это ошибка?Возможно.

Вот код поддержки для видео выше.

activity_main.xml

<ScrollView 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFFFF"
    android:fillViewport="true"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bubble_background"
            android:clickable="true" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bubble_background"
            android:backgroundTint="@color/background_tint"
            android:clickable="true" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bubble_background"
            android:backgroundTint="@color/background_tint"
            android:clickable="true" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bubble_background"
            android:clickable="true" />

    </LinearLayout>
</ScrollView>

bubble_background.xml

<ripple 
    android:color="#33000000">
    <item android:drawable="@drawable/ninepatch_bubble">
    </item>
</ripple>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private LinearLayout mLayout;
    private ImageView mImageView1;
    private ImageView mImageView2;
    private ImageView mImageView3;
    private ImageView mImageView4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLayout = findViewById(R.id.layout);
        mImageView1 = findViewById(R.id.imageView1);
        mImageView2 = findViewById(R.id.imageView2);
        mImageView3 = findViewById(R.id.imageView3);
        mImageView4 = findViewById(R.id.imageView4);

        int bgTint = getResources().getColor(R.color.background_tint);
        RippleDrawable rippleDrawable =(RippleDrawable) mImageView4.getBackground();
        rippleDrawable.getDrawable(0).setTint(bgTint);
        mImageView4.setBackground(rippleDrawable);

        mLayout.post(new Runnable() {
            @Override
            public void run() {
                mImageView3.getLayoutParams().height = mImageView1.getMeasuredHeight();
                mLayout.requestLayout();
            }
        });
    }
}

colors.xml Они были добавлены в colors.xml:

<color name="background_tint">#2681d8</color>
<color name="ripple_tint">#33000000</color>

ninepatch_bubble.9.png

enter image description here

0 голосов
/ 08 октября 2018

Попробуйте использовать эффект ряби следующим образом:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/White">
    <item android:drawable="@drawable/tooltip_left_top" />
    <item android:id="@android:id/mask">
        <color android:color="@color/your_tooltip_color_code" />
    </item>
</ripple>

Обновите здесь, если это работает.

...