android - Kotlin - как получить доступ к цвету solid внутри пользовательской кнопки фона - PullRequest
0 голосов
/ 16 февраля 2020

У меня есть простой Kotlin проект со следующим кодом:

внутри экрана активности, у меня есть представление списка:

    <ListView
        android:layout_marginTop="90dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ordersListView"
        android:divider="@null"
        android:choiceMode="singleChoice"
        android:listSelector="@android:color/holo_orange_light"
        />

этот просмотр списка использует пользовательский интерфейс строки :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">


<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/white_color">

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:gravity="center_vertical"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:paddingLeft="10dp"
        android:text="Name" />


    <Button
        android:id="@+id/send_0"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="0" />

    <Button
        android:id="@+id/send_1"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:background="@drawable/blue_button"
        android:text="1" />

    <Button
        android:id="@+id/send_2"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="2" />

    <Button
        android:id="@+id/send_3"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:background="@drawable/blue_button"
        android:text="3" />
</RelativeLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@color/colorAccent"/>

</LinearLayout>

Кнопка с id = send_0 использует пользовательскую фигуру, используя этот код:

filename = v24 / blue_button. xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#2E9BCA"
        android:id="@+id/solid_bng"/>

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>

сейчас , Я хочу изменить цвет «solid_bng», когда нажимаю на кнопку с id = «send_0».

как я могу это сделать?

не уверен, если это необходимо: я предоставляю также мой код customAdapter: спасибо за любую помощь

: o)

Olivier

имя файла: CustomAdapter.kt

package fr.ormaa.o_service


import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import java.util.ArrayList



class CustomAdapter(private val context: Context, private val imageModelArrayList: ArrayList<ImageModel>) : BaseAdapter() {

    override fun getViewTypeCount(): Int {
        return count
    }

    override fun getItemViewType(position: Int): Int {

        return position
    }

    override fun getCount(): Int {
        return imageModelArrayList.size
    }

    override fun getItem(position: Int): Any {
        return imageModelArrayList[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }


    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        var convertView = convertView
        val holder: ViewHolder


        convertView = convertView

        if (convertView == null) {

            holder = ViewHolder()

            val inflater = context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

            convertView = inflater.inflate(R.layout.meal_item, null, true)

            holder?.tvname = convertView!!.findViewById(R.id.name) as TextView
            holder?.iv = convertView.findViewById(R.id.imgView) as ImageView

            holder?.send0 = convertView.findViewById(R.id.send_0) as Button
            holder?.send1 = convertView.findViewById(R.id.send_1) as Button
            holder?.send2 = convertView.findViewById(R.id.send_2) as Button
            holder?.send3 = convertView.findViewById(R.id.send_3) as Button


            convertView.tag = holder
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = convertView.tag as ViewHolder
        }

        holder?.tvname!!.setText(imageModelArrayList[position].getNames())
        holder?.iv!!.setImageResource(imageModelArrayList[position].getImage_drawables())


        holder?.send0?.setOnTouchListener(zero_clicked)

        return convertView
    }



    private val zero_clicked = View.OnTouchListener { _, _ ->

        Toast.makeText(context,  "zero clicked", Toast.LENGTH_LONG).show()

        false
    }
    private val one_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val two_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val three_clicked = View.OnTouchListener { _, _ ->
        false
    }




    private inner class ViewHolder {

        var tvname: TextView? = null
        internal var iv: ImageView? = null

        var send0: Button? = null
        var send1: Button? = null
        var send2: Button? = null
        var send3: Button? = null


    }

}

Ответы [ 2 ]

0 голосов
/ 16 февраля 2020

Для этого необходим селектор.

blue_button. xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#2E9BCA" />

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>

blue_button_pressed. xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#00608A" />

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>

, а затем blue_button_selector. xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/blue_button_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/blue_button" />
</selector>

И используйте этот селектор в качестве фона для кнопки.

0 голосов
/ 16 февраля 2020

Поскольку у вас уже есть доступ к вашей кнопке в этом файле, вам следует вызвать функцию setBackgroundColor (), которой вы можете назначить целевой цвет.

https://developer.android.com/guide/topics/ui/controls/button дает немного полезной информации о том, как работают кнопки. https://developer.android.com/reference/com/google/android/material/button/MaterialButton дает более подробную информацию о кнопках материалов.

...