要得到一个查看从XML在Android findViewById()
被用来让我们说一个ListView。Android需要什么才能返回findViewById()?
由于事实findViewById()
返回父查看对象,而不是的ListView对象,我们需要转换findViewById()
ListView控件的ListView =(ListView控件)findViewById的回报(R.id.listView) ;
的findViewById()
输出,而不铸造:
System.out.println(findViewById(R.id.mainListView).getClass()); // class android.widget.ListView
System.out.println(findViewById(R.id.mainListView).getClass().getSimpleName()); // ListView
System.out.println((findViewById(R.id.mainListView) instanceof ListView)); // true
但确实findViewById(),然后返回的ListView对象为什么这里有必要投的findViewById()
回报?
你确定在这种特殊情况下你需要它吗?从文档:“注意:在大多数情况下(取决于编译器支持),结果视图会自动转换为目标类类型,如果目标类类型不受约束,则可能需要显式转换。 (该方法是通用的,并且类型参数将通过您要分配的类型推断出来。) –