0

我是android的新手。我有一个简单的疑问,有没有办法从某个布局中获取小部件的ID而不将其设置为内容视图?我希望从一个类中看不到一个视图。我使用了代码

 View  b = findViewById(R.id.id2);
 b.setVisibility(View.GONE);

但是“id”中的错误,如果没有设置为 contentview 的 java 类中的小部件是否可以获取 id?请帮我。提前致谢 :)

4

3 回答 3

0

您可以单独膨胀视图,然后findViewById在膨胀布局的根部使用。

// inside of Activity, you can use 'this' for the context
LayoutInflater inflater = LayoutInflater.from(context);
View root = inflater.inflate(R.layout.some_layout);
// from your example
View b = root.findViewById(R.id.id2);
b.setVisibility(View.GONE);

然而,此时这些视图不是 Activity 视图层次结构的一部分,用户不会看到。您必须通过使用setContentView(root)ViewGroup在当前视图层次结构中找到 a 并调用来添加它们viewGroup.addView(root)

于 2014-05-21T06:36:33.913 回答
0

你可以这样做

Button filterButton = new Button(YourActivity.this);
filterButton.setVisibility(filterButton.GONE);
于 2014-05-21T06:40:23.403 回答
0

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(view) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

See below link :-

Why findViewById() is returning null if setcontentview() is not called?

'But error in "id",is it possible to get ids if widget from a java class without set as contentview ?? '

You have to create dynamic view then you do not have need to call setcontentview.

how to set setContentView?

Is there a way to set setContentView(int id) dynamically?

于 2014-05-21T06:40:48.033 回答