gpt4 book ai didi

android - 每个列表项中的两个 View

转载 作者:太空狗 更新时间:2023-10-29 15:56:23 50 4
gpt4 key购买 nike

我试图在列表的每个元素中显示两个不同的 View 。两个 View 都是 TextView ,但我希望其中一个 View 用不同颜色包围在一个正方形中。我知道这是可能的,因为我读过它,但我无法正确理解它!

有什么想法吗?

谢谢!

最佳答案

您可以创建自己的 adapter对于列表。适配器决定如何显示列表中的项目。
这是一个例子:

class MyAdapter extends ArrayAdapter<TheObjectsToPopulateYourList>{
public MyAdapter(Context context, int textViewResourceId, ArrayList<TheObjectsToPopulateYourList]> objects) {
super(context, textViewResourceId, objects);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if( convertView== null ) convertView = getLayoutInflater().inflate(R.layout.your_layout, null);

TextView myTextView1 = (TextView)convertView.findViewById(R.id.yourFirstTextView);
myTextView1.setText(getItem(position*2)); //getItem gets the item (String in this case) from the list we specified when creating the adapter.
//position is the current position of the list, and since each position has two items, we have to multiply the position by 2 to get to the right item-list-position.
TextView myTextView2 = (TextView)convertView.findViewById(R.id.yourSecondTextView);
myTextView2.setText(getItem(position*2 +1 ));
myTextView2.setBackgroundColor(0xFFFF00FF); //Any color. Use setBackgroundResource to use a resource object (drawable etc.)

return convertView;
}
}

你还需要 line-layout 来包含你需要的所有元素(这是列表每一行将显示的内容),我们将其命名为“thelinelayoutfile.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="wrap_content"
android:orientation="vertical"
android:padding="15dp">
<TextView
android:id="@+id/yourFirstTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="line1"/>
<TextView
android:id="@+id/yourSecondTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="line2"/>
</LinearLayout>

然后当您初始化您的列表时(也许在您的 onCreate() 方法中?)你打电话

//You can create the list anywhere, or use an array.
//I will create it here, just for the sake of demonstration.
ArrayList<String> myLines = new ArrayList<String>();
myLines.add("item1, line1");
myLines.add("item1, line2");
myLines.add("item2, line1");
myLines.add("item2, line2");

//set the list adapter:
ListView myList = (ListView)findViewById(R.id.whateveryourlistidis);
myList.setAdapter(new MyAdapter(this, R.layout.thelinelayoutfile, myLines));

关于android - 每个列表项中的两个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8476217/

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