Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inflating a xml layout in a custom View class

I have a class View1 that extends View. I want to inflate R.layout.test2.xml in this class View1. I have put a following code in this class

public class View1 extends View {      View view;     String[] countries = new String[] {"India", "USA", "Canada"};      public View1( Context context) {         super(context);         LayoutInflater  mInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);         view=mInflater.inflate(R.layout.test2, null, false);     } } 

From another class Home I want this inflated view to be there for some circumstances , In the Home class I wrote the following code:

public class Home extends Activity{      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.home);         CreateView();        }      public void CreateView() {         LinearLayout lv=(LinearLayout)findViewById(R.id.linearlayout);         View1 view = new View1(Home.this);         lv.addView(view);     } } 

But as I run my project the activity doesn't show me anything.

like image 419
LuminiousAndroid Avatar asked Jun 14 '12 08:06

LuminiousAndroid


People also ask

What does inflating a layout mean?

"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.

Which file is inflated by LayoutInflater class?

The LayoutInflater class is used to instantiate the contents of layout XML files into their corresponding View objects. In other words, it takes an XML file as input and builds the View objects from it.

What does inflating a view do?

An inflate process will: read a layout XML. parsing it. and making Java View object to create the UI (ie viewgroup for container and views for widget)


2 Answers

You can't add views to the View class instead you should use ViewGroup or one of its subclasses(like Linearlayout, RelativeLayout etc). Then your code will be like this:

    public class View1 extends LinearLayout {          View view;         String[] countries = new String[] {"India", "USA", "Canada"};          public View1( Context context) {             super(context);             inflate(context, R.layout.test2, this);         }     } 
like image 58
user Avatar answered Oct 02 '22 15:10

user


Use this

    LayoutInflater li = (LayoutInflater)getContext().getSystemService(infService);     li.inflate(R.layout.test2, **this**, true); 

You must to use this, not null, and change the false parameter (boolean AttachToRoot ) to true

like image 38
Aracem Avatar answered Oct 02 '22 17:10

Aracem