我有一个自定义视图类,所以对于整个视图,我需要检查焦点状态,以查看是否聚焦或不聚焦。
我试过的方法是
用过的 setOnFocusChangeListener { }
回调来检查焦点状态。
请提供一些意见,以防我遗漏了什么。谢谢你
下面是一些代码
CarouselCardView constructor(context) : CustomWidget(context),ViewPager.OnPageChangeListener {
private var currentPage = 0
override fun getLayoutId(): Int {
return R.layout.banner
}
init {
isFocusable = true
isFocusableInTouchMode = true
}
private fun setViewpagerAutoAdvanceFeature(
modelData: List<ContentData>
) {
//Auto scroll logic goes here
}
override fun bindData(modelData: List<ContentData>) {
val pagerAdapter = HeroPagerAdapter(context, model = modelTV,
onClickItem = { position ->
clickListener.onItemSelected(uiComponent, uiComponent.componentItems[position])
},
onLastItemReached = { viewPager.setCurrentItem(0, true) })
viewPager.adapter = pagerAdapter
}
//Call backs don't trigger
setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
Log.e("ANI","On setOnFocusChangeListener showing")
} else {
Log.e("ANI","On setOnFocusChangeListener not showing")
}
}
以下是设计图,供参考
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/heroBanner"
android:background="@drawable/bg_transparent">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="@dimen/grid_900"
android:layout_height="@dimen/grid_380"
android:fitsSystemWindows="true" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/indicator"
android:layout_width="@dimen/grid_900"
android:layout_height="@dimen/grid_1"
android:layout_alignBottom="@+id/viewPager"
app:tabBackground="@drawable/btn_selector"
android:layout_gravity="center_horizontal"
android:background="@android:color/transparent"
android:layout_marginBottom="@dimen/margin_bottom_line_indicator"
app:tabIndicatorHeight="0dp"
app:tabGravity="center" />
</RelativeLayout>
我做了一个custome视图,我试着像你在问题中提供的那样在视图类中调用setOnFocusChangeListener。
setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
Log.e("ANI","On setOnFocusChangeListener showing")
} else {
Log.e("ANI","On setOnFocusChangeListener not showing")
}
}
Android studio给出了一个错误,并说 "期待成员声明",但我可以通过实现OnFocusChangeListener来实现,就像这样
class MyView : View, View.OnFocusChangeListener {
...
override fun onFocusChange(v: View?, hasFocus: Boolean) {
}
}