I have following main layout:
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<ViewFlipper android:id="@+id/viewstack"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- Here I want to add my views which are located in separated xml files. -->
</ViewFlipper>
</LinearLayout>
Here is example of my view:
view_url.xml
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:gravity="center">
<EditText android:text="@+id/EditText01"
android:id="@+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnGenerate"
android:text="Generate"/>
</LinearLayout>
view_text.xml
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<EditText android:text="@+id/EditText01"
android:id="@+id/EditText01"
android:layout_height="wrap_content"
android:contentDescription="Enter your text here"
android:layout_width="fill_parent"
android:height="200dp"/>
</LinearLayout>
I am trying to add views:
viewstack = (ViewFlipper) findViewById(R.id.viewstack);));
View viewText = (View) findViewById(R.layout.view_text);
viewstack.addView(viewText); < -- Emulator is crashing at this line
View viewUrl = (View) findViewById(R.layout.view_url);
viewstack.addView(viewUrl);
I dont have any idea what is wrong with my code. I decided to put all my views in one file, but I still want to know how to fix my initial code.
Yout View viewUrl = (View) findViewById(R.layout.view_url);
is very wrong. findViewById is kinda like the get(String key) method the the directory where your directory is your current view/activity. It only looks up the element with that Id under it's children.
To create Java objects out of XML files you need use you need to use the LayoutInflater. Which is pretty straight forward, out of that you get the object you can pass to viewstack.addView(..) method.
Another way to achieve this would be to just include the other XML files into the first one by using either the include, merge tags, or the ViewStub. Depending on your requirements these might not be an option though, but what you are describing they should be, and you should use these instead of doing it programatically because it's just cleaner this way.