您好,登錄后才能下訂單哦!
可以通過繼承BaseAdapter類來自定義ListView的Adapter。以下是一個簡單的例子:
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mDataList;
public CustomAdapter(Context context, ArrayList<String> dataList) {
this.mContext = context;
this.mDataList = dataList;
}
@Override
public int getCount() {
return mDataList.size();
}
@Override
public Object getItem(int position) {
return mDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.list_item, null);
}
TextView textView = view.findViewById(R.id.text_view);
textView.setText(mDataList.get(position));
return view;
}
}
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:padding="8dp"
android:gravity="center_vertical"/>
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private ArrayList<String> mDataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.list_view);
mDataList = new ArrayList<>();
mDataList.add("Item 1");
mDataList.add("Item 2");
mDataList.add("Item 3");
CustomAdapter adapter = new CustomAdapter(this, mDataList);
mListView.setAdapter(adapter);
}
}
通過以上步驟,我們就完成了一個簡單的自定義Adapter來顯示ListView中的數據。可以根據實際需求進行更復雜的定制化操作。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。