适用于ListView的Android自定义行项目

我有一个ListView,其行中应具有以下布局:

HEADER

Text

HEADER应该是静态的,但Text每隔几秒钟就会更改一次。

我通过填充String[] array,将其传递给ArrayAdapter并在每次数据更改时进行设置来实现它:

data_array = populateString();

adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, data_array);

listView.setAdapter(adapter);

我的问题是我不知道如何以上述格式显示数据。

提前致谢。

回答:

将此row.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:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/text"/>

</LinearLayout>

使你的主要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" >

</ListView>

</LinearLayout>

这是你的适配器

class yourAdapter extends BaseAdapter {

Context context;

String[] data;

private static LayoutInflater inflater = null;

public yourAdapter(Context context, String[] data) {

// TODO Auto-generated constructor stub

this.context = context;

this.data = data;

inflater = (LayoutInflater) context

.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override

public int getCount() {

// TODO Auto-generated method stub

return data.length;

}

@Override

public Object getItem(int position) {

// TODO Auto-generated method stub

return data[position];

}

@Override

public long getItemId(int position) {

// TODO Auto-generated method stub

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

// TODO Auto-generated method stub

View vi = convertView;

if (vi == null)

vi = inflater.inflate(R.layout.row, null);

TextView text = (TextView) vi.findViewById(R.id.text);

text.setText(data[position]);

return vi;

}

}

你的Java活动

public class StackActivity extends Activity {

ListView listview;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

listview = (ListView) findViewById(R.id.listview);

listview.setAdapter(new yourAdapter(this, new String[] { "data1",

"data2" }));

}

}

以上是 适用于ListView的Android自定义行项目 的全部内容, 来源链接: utcz.com/qa/405668.html

回到顶部