您好,登錄后才能下訂單哦!
要自定義ListView的Item樣式,可以通過創建一個自定義的布局文件來定義每個Item的外觀和布局。以下是一個簡單的示例:
<?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="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ic_launcher_background"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Item Text"
android:textSize="16sp"/>
</LinearLayout>
public class CustomAdapter extends ArrayAdapter<String> {
private Context mContext;
private List<String> mList;
public CustomAdapter(Context context, List<String> list) {
super(context, R.layout.list_item_layout, list);
this.mContext = context;
this.mList = list;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item_layout, parent, false);
}
ImageView imageView = view.findViewById(R.id.imageView);
TextView textView = view.findViewById(R.id.textView);
imageView.setImageResource(R.drawable.ic_launcher_foreground);
textView.setText(mList.get(position));
return view;
}
}
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
List<String> dataList = new ArrayList<>();
dataList.add("Item 1");
dataList.add("Item 2");
dataList.add("Item 3");
CustomAdapter adapter = new CustomAdapter(this, dataList);
listView.setAdapter(adapter);
}
}
通過以上步驟,就可以自定義ListView的Item樣式了。可以根據需求修改自定義布局文件和適配器中的代碼來實現不同樣式的Item。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。