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.
"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.
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.
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)
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); } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With