How to inflate View on my layout?
-
28-10-2019 - |
Question
How to inflate View on layout, where all my ui elements which are on layout should be visible. Am trying this lines but it is not working am not able to see my background image, button and other images.
MyView view1=new MyView(this);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view1= (MyView) inflater.inflate(R.layout.main, null);
Please help.. Thanks in advance.
Solution
For what you are doing, use
setContentView(R.layout.main);
The reason for not getting your view after inflating is that you need to add that View in the current View somewhere. Currently your inflated view is orphaned.
OTHER TIPS
this usually works...
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view1= inflater.inflate(R.layout.main, null);
or
LayoutInflater inflater = LayoutInflater.from(getApplicationContext);
View view1= inflater.inflate(R.layout.main, null);
and then add this view to the contentView.
Updated:
Assuming you have need to draw a line in your main.xml, let me give you this suggestion. instead of drawing line at runtime by extending View class, create a View in xml like this
<View android:layout_width = "fill_parent"
android:layout_height = "2dp" //assuming you want line of 2dp thickness
android:background= "@android:color/black"/> // define your desired color here
hope it helps..
This worked finally.
getWindow().addContentView(view1,
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));