gpt4 book ai didi

java - ListView 的 Android 自定义行项目

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:27:17 25 4
gpt4 key购买 nike

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

HEADER
Text

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

我通过填充一个 String[] 数组 来实现它,将它传递给一个 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 Activity

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" }));
}
}

结果

enter image description here

关于java - ListView 的 Android 自定义行项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17983481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com