如何通过本地JSON资源文件创建包含3行的动态ListView?
Got it, let's walk through this step by step—super straightforward once you break it down. I'll assume we're working with Android since that's where ListView is commonly used, but the core logic translates to other platforms too.
1. Prepare Your Local JSON File
First, create an assets folder in your Android project (if you don't have one already: right-click app > New > Folder > Assets Folder). Inside it, add a file named data.json with your 3 items. Here's a sample structure:
[ { "title": "First Item", "description": "This is the first row content" }, { "title": "Second Item", "description": "This is the second row content" }, { "title": "Third Item", "description": "This is the third row content" } ]
2. Create a Data Model Class
We need a class to map each JSON object to a Java object. Let's call it ListItem.java:
public class ListItem { private String title; private String description; // Getters and setters public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
3. Design Your Layouts
Main Layout (activity_main.xml)
Add a ListView to your main layout:
<?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="match_parent" android:orientation="vertical"> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
List Item Layout (list_item.xml)
Create a layout for each row in the ListView:
<?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:padding="16dp" android:orientation="vertical"> <TextView android:id="@+id/item_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold"/> <TextView android:id="@+id/item_description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="@android:color/darker_gray" android:layout_marginTop="4dp"/> </LinearLayout>
4. Parse the Local JSON File
We'll read the JSON from the assets folder and convert it into a list of ListItem objects. I'll use Gson for parsing (add implementation 'com.google.code.gson:gson:2.10.1' to your app-level build.gradle if you haven't already).
Here's a helper method to read and parse the JSON:
private List<ListItem> parseJsonFromAssets() { List<ListItem> itemList = new ArrayList<>(); try { // Read JSON file into string InputStream inputStream = getAssets().open("data.json"); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); String json = new String(buffer, StandardCharsets.UTF_8); // Parse JSON to list of ListItem Gson gson = new Gson(); itemList = Arrays.asList(gson.fromJson(json, ListItem[].class)); } catch (IOException e) { e.printStackTrace(); } return itemList; }
5. Create a Custom Adapter
We need an adapter to bind our data to the ListView. Let's make a CustomListAdapter:
public class CustomListAdapter extends BaseAdapter { private Context context; private List<ListItem> itemList; public CustomListAdapter(Context context, List<ListItem> itemList) { this.context = context; this.itemList = itemList; } @Override public int getCount() { return itemList.size(); } @Override public Object getItem(int position) { return itemList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false); holder = new ViewHolder(); holder.titleTextView = convertView.findViewById(R.id.item_title); holder.descriptionTextView = convertView.findViewById(R.id.item_description); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } ListItem item = itemList.get(position); holder.titleTextView.setText(item.getTitle()); holder.descriptionTextView.setText(item.getDescription()); return convertView; } static class ViewHolder { TextView titleTextView; TextView descriptionTextView; } }
6. Bind Everything Together in Your Activity
Finally, in your MainActivity.java, initialize the ListView, parse the JSON, set the adapter:
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.list_view); // Parse JSON and get item list List<ListItem> itemList = parseJsonFromAssets(); // Set adapter to ListView CustomListAdapter adapter = new CustomListAdapter(this, itemList); listView.setAdapter(adapter); } // Include the parseJsonFromAssets method here from step 4 private List<ListItem> parseJsonFromAssets() { // ... (same code as before) } }
That's it! Run your app, and you'll see a 3-row ListView populated with data from your local JSON file. If you need to adjust the number of rows later, just update the JSON file—no need to change the adapter or activity code.
内容的提问来源于stack exchange,提问作者user5649904

