Android : Trying to set width of a textView inside getView() of ListAdapter

on Thursday, January 8, 2015



public View getView(int position, View convertView, ViewGroup parent){
View V = convertView;

if(V == null){
LayoutInflater vi =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
V = vi.inflate(R.layout.barlist_row, null);

}

BarListItem ci = mBarList.get(position);
double likes_cnt = ci.getLikes();
double dislikes_cnt = ci.getDislikes();

TextView likes = (TextView)V.findViewById(R.id.prg_likes);
TextView dislikes = (TextView)V.findViewById(R.id.prg_dislikes);
TextView title = (TextView)V.findViewById(R.id.txt_title);
TextView distance = (TextView)V.findViewById(R.id.txt_distance);

if(likes_cnt > dislikes_cnt){
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics());
likes.getLayoutParams().width = Math.round(px);
px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150*((float)ci.getDislikes()/(float)ci.getLikes()), r.getDisplayMetrics());
dislikes.getLayoutParams().width = Math.round(px);
}else{
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics());
dislikes.getLayoutParams().width = Math.round(px);
px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,150*((float)ci.getLikes()/(float)ci.getDislikes()), r.getDisplayMetrics());
likes.getLayoutParams().width = Math.round(px);
}

title.setText(ci.getTitle());
likes.setText(" " + String.valueOf(ci.getLikes()));
dislikes.setText(" " + String.valueOf(ci.getDislikes()));
distance.setText(String.valueOf(ci.getDistance()) + " miles");

return V;
}


So for this app I have made a custom List Adapter. Everything is working quite well, but the width of the textView's inside of each row of my listView are not correct.


The point of these textViews is to illustrate with image and text, the likes and dislikes count for a bar. I cannot insert an image into the question but I will try to explain. I am working with 150 dp. So if a bar has one like and 0 dislikes, it should look like this


likes -------------- dislikes


notice there is nothing showing for dislikes.


If a bar has 5 likes and 1 dislike it will be proportional to the 150 dp SO:


likes ---------------


dislikes---


THE PROBLEM IS that the textViews sometimes are right then randomly there wil be a false illustraion like the following:


likes = 10


dilikes = 0


likes -------


dislikes ------------------


OR


likes - 0


dislikes - 0


likes --------------------


dislikes ---------


0 comments:

Post a Comment