Java Android,如何在 OnClick 中从 TextView 获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23060792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android, How can I get text from TextView in OnClick
提问by Lo?c
I have some TextView
and each have an OnClickListener
. I would like get information in this method to TextView
我有一些TextView
,每个都有一个OnClickListener
. 我想通过这种方法获取信息TextView
TextView tv2 = new TextView(this,(String)book.get(i),this);
tv2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Contact.this,Discution.class);
//String str = this.getText(); //like this
startActivity(intent);
}
});
How can I do : this.getText();
in an OnClickListener
?
我该怎么办:this.getText();
在一个OnClickListener
?
采纳答案by Sagar Maiyad
tv2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Contact.this,Discution.class);
String str = tv2.getText().toString();
startActivity(intent);
}
回答by Phant?maxx
Just use: tv2
in place of this
.
只需使用:tv2
代替this
.
回答by Raghunandan
This is wrong
这是错误的
TextView tv2 = new TextView(this,(String)book.get(i),this);
You will need TextView to be final and the constructor should match any of the below
您将需要 TextView 为 final 并且构造函数应匹配以下任何一项
TextView(Context context)
TextView(Context context, AttributeSet attrs)
TextView(Context context, AttributeSet attrs, int defStyle)
It should be
它应该是
final TextView tv2 = new TextView(this);
You are not using any of the above. Totally wrong
您没有使用上述任何一种。完全错误
Then inside onClick
然后在onClick里面
String str = tv2.getText().toString();
Its declared final cause you access tv2 inside annonymous inner class.
它声明的最终原因是您在匿名内部类中访问 tv2。
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing
You can also use the View v
.
您也可以使用View v
.
TextView tv = (TextView) v;
String str = tv.getText().toString();
回答by Zohra Khan
Use this
用这个
tv2.getText().toString;
tv2.getText().toString;