-主界面布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
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=".MainActivity">
<ListView
android:id="@+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
-adapter布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="vertical">
<TextView
android:id="@+id/tv_main_content"
android:text="content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
-adapter,java写法:
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return 40;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_adapter, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_main_content.setText("content"+position);
return convertView;
}
class ViewHolder {
final View itemView;
final TextView tv_main_content;
ViewHolder(View itemView) {
this.itemView = itemView;
tv_main_content = itemView.findViewById(R.id.tv_main_content);
}
}
}
-主界面写法:
class MainActivity : AppCompatActivity() {
val listView by lazy { findViewById<ListView>(R.id.lv_main) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
listView.adapter=MyAdapter()
}
}
-adapter,kotlin写法:
class MyAdapter : BaseAdapter() {
override fun getCount(): Int {
return 40
}
override fun getItem(position: Int): Any {
return position
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(
position: Int,
convertView: View,
parent: ViewGroup
): View {
var convertView = convertView
var viewHolder: ViewHolder? = null
if (convertView == null) {
convertView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_adapter, parent, false)
viewHolder = ViewHolder(convertView)
convertView.tag = viewHolder
} else {
viewHolder = convertView.tag as ViewHolder
}
viewHolder.tv_main_content.text = "content$position"
return convertView
}
internal inner class ViewHolder(val itemView: View) {
val tv_main_content: TextView
init {
tv_main_content = itemView.findViewById(R.id.tv_main_content)
}
}
}
网友评论