Reputation: 303
I'm creating an array adapter for list view with 2 items (2 textViews).
I know how to add a single item to my adapter:
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.newsrow, R.id.titleTextView,myArray);
list.setAdapter(listAdapter);
But what should I do to add second textView (called contentTextView in my app) to the listAdapter?
Upvotes: 2
Views: 5617
Reputation: 968
Create your custom layout for your row.
custom_row.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/listview_layout">
<TextView
android:id="@+id/listview_firsttextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</TextView>
<TextView
android:id="@+id/listview_secondtextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</TextView>
</LinearLayout>
Afterwards you will need a custom ArrayAdapter. To achieve this you will need to extend ArrayAdapter<> class, example below:
public class CustomAdapter extends ArrayAdapter<String>
{
private Context context;
private List<String> strings;
public ListViewAdapter(Context context, List<String> strings)
{
super(context, R.layout.listview_row, order);
this.context = context;
this.strings = new ArrayList<String>();
this.strings = strings;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.listview_row, parent, false);
TextView your_first_text_view = (TextView) rowView.findViewById(R.id.listview_firsttextview);
TextView your_second_text_view = (TextView) rowView.findViewById(R.id.list_secondtextview);
your_first_text_view.setText(strings.get(position));
your_second_text_view.setText(strings.get(position)); //Instead of the same value use position + 1, or something appropriate
return rowView;
}
}
And for the last steps set the adapter to the appopriate ListView like this:
ListView my_list_view = (ListView) findViewById(R.id.mylistview);
CustomAdapter my_adapter = new CustomAdapter(this, my_strings);
my_list_view.setAdapter(my_adapter);
I hope this gives you an idea of setting custom adapters to your ListView.
Upvotes: 5