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();
    }
}

当我在 Eclipse 中调试上面的代码时,视图的值在变量窗口中显示为空。问题是什么?或者是否有任何其他方法可以设置 textview 的 ID,并在不使用 XML 文件的情况下从该特定 ID 检索该文本视图。

4

1 回答 1

5

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

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

于 2011-03-09T11:35:38.683 回答