我正在尝试操作不在 Activity 自己的布局 View 上的组件。我将如何引用它们?
我有资源 ID,但当我尝试使用以下方式引用它们时:
DatePicker date = ((DatePicker) findViewById(resID));
.. 我得到一个 NullPointerException。
最佳答案
如果你想在不同的布局 xml 文件中获取 View ,最好的做法是使用 LayoutInflater膨胀(加载)这些文件。你可以这样做:
LayoutInflater inflater;
View firstView;
View secondView;
Button aboutFirst;
Button aboutSecond;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);//initialize the layout inflater
firstView = inflater.inflate(R.layout.firstview, null); // inflate firstview.xml layout file
secondView = inflater.inflate(R.layout.secondview, null);//inflate secondview.xml layout file
aboutFirst = (Button) firstView.findViewById(R.id.button1);//get button in firstview.xml
aboutSecond = (Button) secondView.findViewById(R.id.button1);//get button in secondview.xml
}
关于android - 如何获取不在Acitivty自身布局上的布局组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9556069/