Search code examples
javaandroidandroid-layoutandroid-relativelayout

how to get access RelativeLayout as a variable?


I can't figure out how to access my RelativeLayout programmatically so that I could call a method such as relativeLayout.getChildCount(); inside a Handler.

Edit - alright, if I wanted to get the total number of Views in my RelativeLayout, what function would I call?


Solution

  • In folder res/layout, I assume your layout named layout.xml

    1. make sure your RelativeLayout have android:id segment

      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:id="@+id/myRelativeLayout" > //the id name can be acsessed in activity
      
              <TextView
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:text="@string/hello_world" />
      
      </RelativeLayout>
      
    2. access that RelativeLayout id in activity

      public class mainActivity extends Activity {
          //make variable globally
          RelativeLayout myRelativeLayout;
      
      
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              //the layout file
              setContentView(R.layout.layout);
      
              //access the RelativeLayout and initialiszed the object
              myRelativeLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);
              myRelativeLayout.getChildCount();
      
          }
      }