inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[초급편] 안드로이드 커뮤니티 앱 만들기(Android Kotlin)

textview에 이미지 삽입하고 이미지만 클릭가능하게만들기

548

hskim9337

작성한 질문수 8

0

<TextView
    android:id="@+id/tv_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ellipsize="end"
    android:maxLines="1"
    android:padding="5dp"
    android:text="title"
    android:drawableRight="@drawable/ic_baseline_delete_24"
    android:drawablePadding="5dp"
    android:clickable="true"
    android:textSize="18sp" />

이런식으로 하면

 

이렇게 처리가 되더라구요

근데 저는 우측에 저 쓰레기통 눌렀을때만 액션이 발생했으면 좋겠는데 이런경우에는 어떻게 커스텀할수있나요?

사실 그냥 이미지뷰 나눠서 넣으면 상관없긴한데 혹시 가능한가싶어서요

 

firebase kotlin android

답변 3

0

개복치개발자

이런식으로 ViewHolder에서 onClick 이벤트를 처리해보시겠어요?

class IntroRVAdapter (val context : Context, val dataSet : List<CurrentPriceResult>)
    : RecyclerView.Adapter<IntroRVAdapter.ViewHolder>() {

    private val TAG = IntroRVAdapter::class.java.simpleName
    val coinList = ArrayList<String>()

    init {
        Log.d(TAG, "init")
    }

    inner class ViewHolder(view : View) : RecyclerView.ViewHolder(view) {

        val coinName : TextView = view.findViewById(R.id.coinName)
        val coinPriceUpDown : TextView = view.findViewById(R.id.coinPriceUpDown)
        val likeImage : ImageView = view.findViewById(R.id.likeBtn)

        init {

            likeImage.setOnClickListener {

                Log.d(TAG, "onCLicked")
                Log.d(TAG, dataSet[adapterPosition].toString())

                val currentCoinName = dataSet[adapterPosition].coinName

                if(coinList.contains(currentCoinName)) {
                    // 포함할 때
                    likeImage.setImageResource(R.drawable.like_grey)
                    coinList.remove(currentCoinName)
                } else {
                    // 포함하지 않을 때
                    coinList.add(currentCoinName)
                    likeImage.setImageResource(R.drawable.like_red)
                }


            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val view = LayoutInflater.from(parent.context).inflate(R.layout.intro_coin_item, parent,false)

        return ViewHolder(view)

    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.coinName.text = dataSet[position].coinName

        val fluctate_24H = dataSet[position].coinInfo.fluctate_24H

        if(fluctate_24H.contains("-")) {
            holder.coinPriceUpDown.text = "하락입니다."
            holder.coinPriceUpDown.setTextColor(Color.parseColor("#114fed"))
        } else {
            holder.coinPriceUpDown.text = "상승입니다."
            holder.coinPriceUpDown.setTextColor(Color.parseColor("#ed2e11"))
        }
        
        if(coinList.contains(dataSet[position].coinName)) {
            holder.likeImage.setImageResource(R.drawable.like_red)
        } else {
            holder.likeImage.setImageResource(R.drawable.like_grey)
        }



    }

    override fun getItemCount(): Int {
        return dataSet.size
    }


}

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="80dp">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/coinName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:layout_marginLeft="20dp"
                android:text="coinName"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />


            <TextView
                android:id="@+id/coinPriceUpDown"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="coinPriceUpDown"
                android:layout_marginLeft="20dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toEndOf="@+id/coinName"
                app:layout_constraintTop_toTopOf="parent" />


            <ImageView
                android:id="@+id/likeBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/like_grey"
                android:layout_marginRight="20dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>


</androidx.constraintlayout.widget.ConstraintLayout>

 

0

hskim9337

감사합니다

0

hskim9337

class MyViewHolder(private val binding: ItemListBinding):RecyclerView.ViewHolder(binding.root) {

    fun bind(item:Data) {
        with(binding) {
            tvId.text = item.Num
            tvTitle.text = item.title
        }

    }
    

}

 

myviewholder.kt

 

class MyListAdapter:ListAdapter<Data,RecyclerView.ViewHolder>(MyDiffCallback()) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        val viewHolder = MyViewHolder(
            ItemListBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )

        )
        return viewHolder
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is MyViewHolder) {
            val items = getItem(position) as Data
            holder.bind(items)
        }
    }

}

 

myListadapter.kt

 

이런식으로 짠 상태입니다.

 

아래가 item_list이구요.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/vhlayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/selectableItemBackground"
    android:baselineAligned="false"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="9"
        android:orientation="horizontal">

        <TextView

            android:id="@+id/tv_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:ellipsize="end"
            android:maxLines="1"
            android:padding="3dp"
            android:text="id"
            android:textSize="24sp" />


        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ellipsize="end"
            android:maxLines="1"
            android:padding="5dp"
            android:text="title"
            android:drawableRight="@drawable/ic_baseline_delete_24"
            android:drawablePadding="5dp"
            android:clickable="true"
            android:textSize="18sp" />


    </LinearLayout>

</LinearLayout>

0

개복치개발자

전체 item click이 아니라, 저 휴지통 이미지만 말씀하시는게 맞으시다면

adapter에 viewHolder안에서 itemClick 이벤트를 처리해주시면 됩니다.

(아래의 예제 코드 첨부드립니다.)

이해가 어려우시다면 어떻게 시도하셨는지 코드를 공유해주세요.

 

inner class ViewHolder(view : View) : RecyclerView.ViewHolder(view) {


    val likeImage : ImageView = view.findViewById(R.id.likeBtn)

    init {

        likeImage.setOnClickListener {

            Log.d(TAG, "onCLicked")
          


        }
    }

}

이미지가 기본이미지인지 확인

0

143

1

NavController error 발생

0

156

1

fragment 생성하고 메인에서 불러왔는데 안뜹니다.

0

151

2

67강 댓글

0

113

2

7강 데이터바인딩 에러

0

129

2

Firebase 스토리지 유료화 문제

1

309

2

게시글 이미지가 파이어베이스에 저장되지 않습니다.

0

192

2

AVD 갤러리에 이미지 저장 안되는 문제

0

257

2

이미지 받아오는 방법?

0

213

2

회원탈퇴 기능을 추가하려고 합니다.

0

199

2

상태바 질문 드립니다.

0

120

1

섹션2 인트로 페이지 꾸미기 질문 드립니다.

0

124

1

게시판 글을 길게 쓸경우

0

131

2

로그인 로그아웃

0

188

2

갤럭시 연결시 게시판에 업로드한 사진이 보이지 않아요.

0

223

2

웹뷰 AVD 실행안됨

0

201

1

자막켜기가 안되요 ㅜ.ㅜ

1

199

1

리사이클러뷰, 그리드레이아웃 오류

0

194

2

리사이클러뷰 오류 해결 방법이 궁금합니다.

0

204

1

firebase 스마트폰으로 연결이 안되는데 원인이 있을까요

0

274

2

안드로이드 스튜디오 게시글 이미지 업로드 유무

0

230

1

firebase 설정 오류

0

312

2

홈 화면 커뮤니티

0

183

1

게시판 글 읽기

0

247

2