对于findViewById的一点点醒悟
2013-10-10 17:33
176 查看
1.一个月写过不少的Android Demo,一直不太清楚那个findViewById,只知道它就是通过
控件的Id就可以获取该控件....
2.今天我居然顺手写出了几行这样的代码...
public class HelloWorld extends Activity { /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); LinearLayout myLayout = (LinearLayout)findViewById(R.layout.test1); TextView tView = new TextView(this); tView.setText("Hello"); myLayout.addView(tView); setContentView(myLayout); } }
编译时没有错的,运行的时候就报空指针....
3.仔细想了想,为什么之前findViewById可以找到控件,现在却出错了...
总结了下:
findViewById,如果是单单用findViewById的话,会从该Activity指定的布局文件里面去找
要找某一个布局文件的控件的话,要这样子写:
LinearLayout myLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.test1, null);
首先通过布局加载器加载该布局,然后在该布局中找到某一控件
TextView tView = (TextView)myLayout.findViewById(R.id.XX);
4.因此我的代码如果要成功的运行的话,要这样子写
public class HelloWorld extends Activity { /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //通过布局加载器来加载到你所需要的布局 LinearLayout myLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.test1, null); TextView tv = new TextView(this); tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); tv.setText("Hello"); //将TextView加入该布局文件中 myLayout.addView(tv); //设置该Activity的contentView setContentView(myLayout); } }[code]5.嗯,有时候一些小问题会搞的你很长时间...还是踏实点吧,少年...
相关文章推荐
- Android 简化 findViewById
- 如何解放findViewById
- 简化 android findviewbyid
- findViewById(R.id.xx)使用位置的放置!
- 关于findViewById
- LayoutInflater和findViewById()
- 求助 android开发中 如果两个控件的id相同 会怎样?如何使用findviewbyid ()寻找到?
- findViewById值为null,报nullpointer错误的问题
- android 减少findViewById 的使用
- android studio 3.0 preview 使用kotlin写android,抛弃findviewbyid
- setContentView切换页面(无需每次都findViewById)-----二
- findViewById() 和 view.findViewById()
- DialogFragment不能findViewById的解决方法
- findViewById 返回null
- LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。 但他是找XML文件并实例化
- [Android-Tips] findviewbyid function returns null
- Android APT开发教程 五 使用注释完成findViewById和setConten
- 如何在Fragment中使用findViewById
- 关于在adapter使用LinearLayout的findviewbyid问题
- 使用Kotlin,抛弃findViewById