如何将RelativeLayout作为变量访问?

时间:2016-04-17 04:30:45

标签: java android android-layout relativelayout

我无法弄清楚如何以编程方式访问RelativeLayout,以便在调用程序中调用relativeLayout.getChildCount();之类的方法。

编辑 - 好吧,如果我想获得RelativeLayout中的视图总数,我会调用哪个函数?

1 个答案:

答案 0 :(得分:0)

在文件夹res / layout中,我假设您的布局名为layout.xml

  1. 确保您的RelativeLayout具有android:id段

    <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. 访问活动中的RelativeLayout ID

    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();
    
        }
    }