Background code
Copy codeThe Code is as follows: private void ChangeView ()
{
Ly. removeAllViews ();
LayoutInflater inflater = (LayoutInflater) getSystemService (LAYOUT_INFLATER_SERVICE );
View layout = inflater. inflate (R. layout. grid, null );
GridView gridview = (GridView) layout. findViewById (R. id. gridview );
Gridview. setAdapter (new ItemAdapter (MainActivity. this ));
Gridview. setOnItemSelectedListener (new OnItemSelectedListener (){
Public void onItemSelected (AdapterView arg0, View arg1,
Int arg2, long arg3 ){
}
Public void onNothingSelected (AdapterView arg0 ){
}
});
Ly. addView (gridview );
}
Code Description:
A). ly is the LinearLayout with the id ContentView in main. xml, that is, the container that needs to dynamically Add the View
B). ItemAdapter is a helper class for Grid data filling.
Symptom
Normal
If you copy and paste the GridView code in grid. xml to the LinearLayout container in main. xml without any problems, the layout is normal.
Abnormal
If you add android: layout_height = "fill_parent" dynamically as shown in the preceding figure, it becomes invalid. No matter whether an absolute value is set here, for example, 300dp, The GridView always displays only the content of the Item, that is, the View in the container cannot completely fill the LinearLayout parent container.
Iii. Solution code
Just one line of code, I don't know if it's an Android Bug or how:
Copy codeThe Code is as follows: ly. addView (gridview, new LinearLayout. LayoutParams (LinearLayout. LayoutParams. FILL_PARENT, LinearLayout. LayoutParams. FILL_PARENT ));
End
I have been bored with this problem for more than two hours.