自定义ListView是指根据自己的需求和设计,对Android平台上的ListView进行个性化定制。下面是制作自定义ListView的步骤:
下面是一个示例代码,演示如何制作自定义ListView:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private List<String> mData;
public CustomAdapter(Context context, List<String> data) {
mContext = context;
mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.textView = convertView.findViewById(R.id.textView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String item = mData.get(position);
viewHolder.textView.setText(item);
return convertView;
}
private static class ViewHolder {
TextView textView;
}
}
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="18sp" />
public class MainActivity extends AppCompatActivity {
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.listView);
List<String> data = new ArrayList<>();
data.add("Item 1");
data.add("Item 2");
data.add("Item 3");
CustomAdapter adapter = new CustomAdapter(this, data);
mListView.setAdapter(adapter);
}
}
这样就完成了一个简单的自定义ListView的制作。你可以根据自己的需求,进一步定制列表项的布局和样式,以及添加更多的交互功能。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云