从视图中获取布局

Lal*_*tar 8 android

我正在使用XML来扩展XML接口

View add_phone = getLayoutInflater().inflate(R.layout.phone_info, null);
Run Code Online (Sandbox Code Playgroud)

现在我如何从add_phone视图访问RelativeLayout?有什么方法getChildCount()吗?

Yas*_*mar 6

是的,getChildCount(),适用于像LinearLayout,RelativeLayout等ViewGroup.

ViewGroup add_phone = (ViewGroup) getLayoutInflater().inflate(R.layout.phone_info, null);
int childCount = add_phone.getChildCount();
Run Code Online (Sandbox Code Playgroud)

您必须确保膨胀的布局将viewGroup作为父视图,否则您将获得类强制转换异常.viewGroup可以是LinearLayout,RelativeLayout等.


nan*_*ack 5

您可以通过以下方式找到视图的子视图

View.findViewById(int id)
Run Code Online (Sandbox Code Playgroud)

在你的情况下,这转化为

RelativeLayout child = (RelativeLayout)add_phone.findViewById(R.layout.phone_info) 
Run Code Online (Sandbox Code Playgroud)

只要您在 add_phone 中的子元素具有唯一 id,这应该返回正确的元素。