【发布时间】:2011-12-12 14:57:01
【问题描述】:
我试图在列表的每个元素中显示两个不同的视图。两个 vews 都是文本视图,但我希望其中一个被包含在具有不同颜色的正方形中。我知道这是可能的,因为我已经阅读过它,但我无法正确理解它!
有什么想法吗?
谢谢!
【问题讨论】:
-
看这个链接,它可以帮助你:stackoverflow.com/questions/4407865/…
我试图在列表的每个元素中显示两个不同的视图。两个 vews 都是文本视图,但我希望其中一个被包含在具有不同颜色的正方形中。我知道这是可能的,因为我已经阅读过它,但我无法正确理解它!
有什么想法吗?
谢谢!
【问题讨论】:
您可以为列表创建自己的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));
【讨论】:
更多细节会有所帮助;我的解决方案可能不准确,因为我不太清楚你想要什么。
查看 View 元素的背景颜色:http://developer.android.com/reference/android/view/View.html#setBackgroundColor(int)。
如果您有两个视图,并将背景颜色设置为不同的值,则可以使每个视图周围都有正方形。这样或许能创造出想要的效果。
【讨论】: