Rakesh
Rakesh

Reputation: 15057

How to get root layout programmatically and set it as content view

I have xml file as specified below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testapp.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

If I want to take relativelayout(_main) and assign it to local relativelayout variable programmatically and then set it as contentview instead of setting as

setContentView(R.layout.activity_main);

I tried other way

main = (RelativeLayout)findViewById(R.id.main);

Still I got the error. What is way of getting it? My aim is to load the custom view to the current layout. How to do it?

Upvotes: 2

Views: 2722

Answers (2)

Bojan Kopanja
Bojan Kopanja

Reputation: 734

I'm not sure if i understood correctly what are you trying to do here, but if you need to fetch root view programmatically and use it later you can do it like this:

RelativeLayout rlMain = (RelativeLayout) getWindow().getDecorView().findViewById(R.id.main)

But as Nauman Afzaal said, you should inflate custom view, rather than add it the way you're trying now.

Upvotes: 3

Nauman Afzaal
Nauman Afzaal

Reputation: 1046

My Aim is to load the custom view to the current layout .How to do it.

You should inflate your custom view to currently added view. You can define any relative layout in your main xml and then inflate your new view inside it.

Upvotes: 1

Related Questions