Я пытаюсь показать два разных представления в каждом элементе списка. Оба vews представляют собой текстовые виды, но я хочу, чтобы один из них был заключен в квадрат с другим цветом. Я знаю, это возможно, потому что я читал об этом, но я не могу понять его правильно!
Есть идеи?
Благодарю!
Вы можете создать свой собственный адаптер для списка. Адаптер определяет, как отображать элементы в списке.
Вот пример:
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;
}
}
И вам также нужен макет строки, чтобы содержать все необходимые вам элементы (это будет отображаться в каждой строке списка), позвольте называть его "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));
Более подробная информация поможет; мое решение может быть неточным, так как я не знаю, что вы хотите очень хорошо.
Проверьте цвет фона элемента "Вид": http://developer.android.com/reference/android/view/View.html#setBackgroundColor (int).
Если у вас есть два вида и задайте цвета фона для разных значений, вы можете заставить каждый вид иметь квадрат вокруг него. Это может создать желаемый эффект.