1

使用此代码,我的程序只是强制关闭(错误)

***public View x = findViewById(R.string.nfoname);***
@Override
public void onCreate(Bundle savedInstanceState) {    
super.onCreate(savedInstanceState);    
setContentView(R.layout.information);
//edittext
***final EditText infoname=(EditText)findViewById(R.id.infoname);***

//clear,confirm
Button clear = (Button)findViewById(R.id.buttonclear);
Button confirm = (Button)findViewById(R.id.buttonconfirm);

//clear button
clear.setOnClickListener(new View.OnClickListener() {       
    public void onClick(View v) {
        // TODO Auto-generated method stub
        infoname.setText("");
    }
});
//confirm button
confirm.setOnClickListener(new View.OnClickListener() {     
    public void onClick(View v) {

        ***x=(View) infoname.getText();***
    }
});
}

*的是错误来源

程序功能:如果用户点击确认,他的名字将被设置为R.string.nfoname,然后通过TextView在另一个布局中使用x = setText(R.string.nfoname);

4

4 回答 4

2

我不确定您是否可以将文本保存到 R.string。这是编译器为您创建的生成类。它与您的 apk 打包在一起。将资源视为一种翻译手段并将文本呈现到屏幕上。

我认为您想要做的是将用户输入保存为 SharedPreference 或数据库中。

有关示例用法,请参阅: android 文档上的SharedPreferences 。

于 2012-01-17T01:34:44.547 回答
0

At least in the case of your variable infoname scoping is most likely causing your application to throw an error. infoname is a local variable to the function onCreate(), not an instance variable for your class, so it can't be accessed by your onClick() methods because they are part of an anonymous class.

Another thing I'd question is why you marked infoname as final? It goes out of scope when onCreate() exits so if it gets changed, you can see who changed it since it only exists while the method is executing.

于 2012-01-17T01:37:42.577 回答
0

您不能将值设置为 R.string.xxx 因为所有这些值都是常量,就像只读的东西一样。如果要将编辑文本的值用于另一个布局,请使用类变量或intent.putextra()

来到你的源代码,我看到了这个

public View x = findViewById(R.string.nfoname);

R.String 如何找到视图?这应该是 R.id。

final EditText infoname=(EditText)findViewById(R.id.infoname); 为什么这个editText必须是最终的?

***x=(View) infoname.getText();***

您只需使用infoname.getText().toString()您将获得 Edittext 的当前文本的字符串值。伙计,你可以简单地做事。

于 2012-01-17T01:43:41.557 回答
0
public View x = findViewById(R.string.nfoname);

这是行不通的,因为您不仅要尝试View使用资源 id 查找,而且要在方法中调用R.string它之前执行此操作。即使您使用了有效的资源 ID,例如then也将是因为内容视图还没有被夸大。setContenView(...)onCreate(...)ViewR.id.infonamexnull

final EditText infoname=(EditText)findViewById(R.id.infoname);

除了毫无意义地使用finalthis 之外,只要R.id.infoname它实际上是一个EditText.

x=(View) infoname.getText();

不仅会x而且null调用getText()a会EditText返回一个Editable不是 aView也不可能将其强制转换为 的View。即使您使用getText().toString()which 是从 a 获取文本的正确方法,EditText仍然无法将 aString转换为 a View

还有,至于这个...

TextView x = setText(R.string.nfoname);

它必须是...

TextView x = (TextView) findViewById(<some id>);
x.setText(getString(R.string.nfoname));
于 2012-01-17T01:53:49.543 回答