Home >Java >javaTutorial >How to Create Custom Row Items for a ListView in Android with a Static Header and Dynamic Text?
This article will showcase how to create custom row items for a ListView in Android, allowing you to display data in specific formats.
The aim is to create a ListView where each row follows a particular layout:
HEADER Text
The HEADER should remain static while the Text will change periodically.
1. Custom Layout XML
Add the following row.xml to your layout folder:
<code class="xml"><?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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Header" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout></code>
2. Main XML Layout
Update your main XML layout to include the ListView:
<code class="xml"><?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <ListView android:id="@+id/listview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout></code>
3. Custom Adapter
Create a custom adapter class that extends BaseAdapter:
<code class="java">class yourAdapter extends BaseAdapter { // ... implementation details ... }</code>
4. Java Activity
In your main Java activity, set up the ListView and adapter:
<code class="java">public class StackActivity extends Activity { ListView listview; @Override protected void onCreate(Bundle savedInstanceState) { // ... implementation details ... listview.setAdapter(new yourAdapter(this, new String[] { "data1", "data2" })); } }</code>
The result will be a ListView with custom row items displaying the desired layout:
HEADER Text
The above is the detailed content of How to Create Custom Row Items for a ListView in Android with a Static Header and Dynamic Text?. For more information, please follow other related articles on the PHP Chinese website!