findviewbyid在android中不起作用

Nir*_*rav 1 android android-sdk-2.1

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class ViewId extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView txtArea = new TextView(this);
        txtArea.setId(20);
        txtArea.setText("Hello");

        TextView view = new TextView(this);
        view = (TextView) this.findViewById(20);
        Toast.makeText(this,view.getText(), Toast.LENGTH_LONG).show();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在eclipse中调试上面的代码时,视图的值在变量窗口中显示为null.问题是什么?或者是否有任何其他方法来seviewd textview并从该特定id中检索该文本视图而不使用XML文件.

War*_*ith 5

你的代码有点乱.首先,使用xml布局设置contentview,这是您从未使用过的.您还可以创建一个TextView txtArea并将id设置为20,这没关系,但是您永远不会将此视图添加到您的内容中,因此您可以稍后找到它.

您必须决定:使用XML进行布局并使用它.您也可以通过编程方式对其进行修改,或者以编程方式创建自己的布局,并将内容视图设置为新创建的布局/视图.