【安卓开发】Kotlin编写DataBinding+RecyclerView组合
Kotlin语言,将DataBinding和RecyclerView结合开头错误自查Unresolved reference: BR在模块的build.gradle中添加Kotlin-apt插件plugins {id 'kotlin-kapt'}kapt {generateStubs = true}不废话,直接代码数据类data class TempText(val mText: String)a
·
Kotlin语言,将DataBinding和RecyclerView结合
开头错误自查
Unresolved reference: BR
在模块的build.gradle中添加Kotlin-apt插件
plugins {
id 'kotlin-kapt'
}
kapt {
generateStubs = true
}
不废话,直接代码
数据类
data class TempText(val mText: String)
adapter
class RecyclerViewLearnAdapter(private val dataTemp : Array<TempText>) :
RecyclerView.Adapter<RecyclerViewLearnAdapter.BindingHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder {
val binding = DataBindingUtil.inflate<ConfigRecyclerViewLearnListItemBinding>(
LayoutInflater.from(parent.context),
viewType,
parent,
false
)
return BindingHolder(binding)
}
override fun onBindViewHolder(holder: BindingHolder, position: Int) {
holder.bindData(dataTemp[position])
}
override fun getItemCount() = dataTemp.size
override fun getItemViewType(position: Int): Int {
return R.layout.config_recycler_view_learn_list_item
}
class BindingHolder(private var binding : ConfigRecyclerViewLearnListItemBinding) : RecyclerView.ViewHolder(binding.root){
fun bindData(tempText: TempText){
binding.setVariable(BR.tempText,tempText)
binding.executePendingBindings()
}
}
}
item的布局文件
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable name="tempText" type="com.example.myapplication.data.TempText" />
</data>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/list_item_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher_background"
android:padding="10dp"
android:text="@{tempText.mText}"
android:textSize="16sp" />
</LinearLayout>
</layout>
activity文件(JAVA)
public class RecyclerViewLearn extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config_recycler_view_learn_activity);
RecyclerView leftRecyclerView=findViewById(R.id.recycle_view_learn_recycleview1);
TempText[] data=new TempText[7];
data[0]=new TempText("12345678");
data[1]=new TempText("azazazaz");
data[2]=new TempText("!!!!!!!!");
data[3]=new TempText("????????");
data[4]=new TempText("########");
data[5]=new TempText("********");
data[6]=new TempText("????????");
LinearLayoutManager leftLayoutManager = new LinearLayoutManager(this);
leftRecyclerView.setLayoutManager(leftLayoutManager);
RecyclerViewLearnAdapter leftAdapter=new RecyclerViewLearnAdapter(data);
leftRecyclerView.setAdapter(leftAdapter);
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)