您的位置:首页 > 其它

对于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.嗯,有时候一些小问题会搞的你很长时间...还是踏实点吧,少年...

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: