Search code examples
androidlistviewandroid-listviewwidthlayoutparams

Change width of a ListView item(row)?


I have a ListView that every row shows different percentage.

and I wanna change one of inner layouts width (inside inflated counterView) for this purpose .

for example:

if first value item in listview is 10% then width set to 10px too

if second value item is 50% then width change to 50px too

something like this:
enter image description here

How can I do that ?

I tried these codes but it doesn't work and the width doesn't change: (I defined match_parent width for layout inside XML and I wanna change it programmatically)

public class MyAdapterScores extends BaseAdapter {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView  = layoutInflater.inflate(R.layout.scores_layout,null,true);

            //I wanna change 'relativeLayoutRightSqure' width inside 'scores_layout'
            View layout = convertView.findViewById(R.id.relativeLayoutRightSqure);
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) layout.getLayoutParams();
            //variable precentage has value                 
            p.width=precentage ;
            layout.requestLayout();

Solution

  • I found the problem !

    the problem was defining android:layout_toRightOf and android:layout_toLeftOf for my inner counterView layout view simultaneously that causes setting width doesn't work !!

    ( Referred to above code (relativeLayoutRightSqure):

    View layout = convertView.findViewById(R.id.relativeLayoutRightSqure);
    

    )