Inflate a custom view from XML, then set her height and witdh programmatically



I'm loosing myself in an custom size View problem since a couple of days. After some long research, I finally decide to ask your help... please ! T_T


In my app, I created a custom View with the XML calendrieradmin_day.xml :



<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://ift.tt/nIICcg"
android:id="@+id/CalendrierAdmin_Day_Event_TableRow"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<!-- <TextView
android:id="@+id/CalendrierAdmin_Day_Event_TextView_Name"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center" />-->
</TableRow>


For now, it is a simple TableRow, but I'll need to add some other things in the future. (The commented TextView, for example).


I made three classes for using it : Row, EventRow and EmptyRow. Row is abstract and EventRow and EmptyRow inherit of Row. Also, Row inherit of TableRow.


I want to add several EventRow and EmptyRow in a TableLayout and I need to resize them dynamically.


In the constructor method of EmptyRow and EventRow, I call an init() method :



private void init(Context c, TableLayout root) {
root = (TableLayout)LayoutInflater.from(c).inflate(R.layout.calendrieradmin_day_event, root, true);

LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) root.getLayoutParams();

lp.height = getHeightOfMinute() * getDuree();
lp.width = getTheWidth();

/*
Some other stuff
...
...
*/

this.setLayoutParams(lp);

root.addView(this);

setOnClickListener(this);
setOnLongClickListener(this);
}


root is my TableLayout I pass in the constructor. getHeightOfMinute() and getDuree() work correctly and give me the right sizes. I used to use the inflate() method like inflate(R.layout.calendrieradmin_day_event, null, false) and it worked fine, but Eclipse gave me a warning, telling me I shouldn't pass null as the RootView argument. Although everything worked fine, I begun to search another solution and this is where I gone so far...


I used the setMinimumHeight() and setMinimumWidth() method to rezise my EventRow and EmptyRow. It works, but I think there is a better way to do that. I tried A LOT of solutions but I messed up ! I think there is something I still not catched about the functioning of inflate() and/or LayoutParams.


Could you help me ? Thanks in advance !


PS: Sorry for the bad english, I'm french.


No comments:

Post a Comment