[英]Android, How can I get text from TextView in OnClick
I have some TextView
and each have an OnClickListener
.我有一些
TextView
并且每个都有一个OnClickListener
。 I would like get information in this method to TextView
我想在这个方法中获取信息到
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();
我该怎么办:
this.getText();
in an OnClickListener
?在
OnClickListener
?
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();
tv2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Contact.this,Discution.class);
String str = tv2.getText().toString();
startActivity(intent);
}
只需使用: tv2
代替this
。
用这个
tv2.getText().toString;
Lets suppose you have this in your layout:假设您的布局中有这个:
<TextView android:id ="@+id/myText"
android:layout_width ="wrap_content"
android:layout_height="wrap_content"
android:textSize ="26dp"
android:text ="bla bla bla..."
android:textColor ="#0000ff"
android:clickable ="true"
android:onClick ="onMyClick"/>
Now lets get the text content from myText element when it gets clicked现在让我们在点击时从myText元素中获取文本内容
public void onMyClick(View v)
{
TextView t=(TextView)v;
String s=t.getText().toString();
//do whatever you want with the string s
}
Note the boolean android:clickable="true" on the layout element [ it's mandatory ]
注意布局元素上的布尔值android:clickable="true" [这是强制性的]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.