Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid: alternate background color in a TableLayout inside a ListView
    text
    copied!<p>I'm trying to display a set of data in a Grid style, using a TableLayout inside a ListView. What I want is to display each row with a different color (two colors alternatively). It works well when using a normal LinearLayout in the ListView, but for whatever reason when using a TableLayout I end up having all rows having the same background, which I think is the last one set.</p> <p>For this, I am using a BaseAdapter, and in the getView function I have something like:</p> <pre><code>public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.list, parent, false); holder = new ViewHolder(); holder.from = (TextView) convertView.findViewById(R.id.from); holder.to = (TextView) convertView.findViewById(R.id.to); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if(position%2==0) { convertView.setBackgroundColor(R.color.cell_background); } //alternate background else { convertView.setBackgroundColor(R.color.cell_background_alternate); } // Bind the data efficiently with the holder. holder.from.setText(list.get(position)[0]); holder.to.setText(list.get(position)[1]); return convertView; } </code></pre> <p>Now in my main.xml for the activity, I just have a ListView. In the list.xml used to inflate the list, I have:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;TableRow android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:id="@+id/from" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:layout_weight="1"/&gt; &lt;TextView android:id="@+id/to" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:layout_weight="1"/&gt; &lt;/TableRow&gt; &lt;/TableLayout&gt; </code></pre> <p>Also, another problem is that the columns are not aligned: it just takes as much space as it needs for every row, every columns, when a TableLayout should align all columns. The only workaround that I came up with was to set a minimal width for the columns, but that's not pretty. Any reason why it does not work here?</p> <p>Edit 21/06: <img src="https://i.stack.imgur.com/7eYIl.png" alt="cell not aligned"></p> <p>As you can see on the picture, the columns are not aligned (row 2 and 3 are but it's obviously because they have the same data inside).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload