Android dynamic View addition Solution

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.