我知道这是如此容易(doh…),但我正在寻找一种方法来运行在一个Android应用程序点击或点击文本的TextView行。
我一直在想按钮监听器和匿名方法监听器调用,但它似乎并不适用于TextView。
有人能指出我在一些代码片段,以显示如何点击或点击在TextView运行一个方法的文本?
我知道这是如此容易(doh…),但我正在寻找一种方法来运行在一个Android应用程序点击或点击文本的TextView行。
我一直在想按钮监听器和匿名方法监听器调用,但它似乎并不适用于TextView。
有人能指出我在一些代码片段,以显示如何点击或点击在TextView运行一个方法的文本?
当前回答
要点击一段文本(不是整个TextView),你可以使用Html或Linkify(两者都创建链接,打开url,虽然不是在应用程序中的回调)。
其内
使用字符串资源,如:
<string name="links">Here is a link: http://www.stackoverflow.com</string>
然后在textview中:
TextView textView = ...
textView.setText(R.string.links);
Linkify.addLinks(textView, Linkify.ALL);
Html
使用Html.fromHtml:
<string name="html">Here you can put html <a href="http://www.stackoverflow.com">Link!</></string>
然后在你的textview中:
textView.setText(Html.fromHtml(getString(R.string.html)));
其他回答
要点击一段文本(不是整个TextView),你可以使用Html或Linkify(两者都创建链接,打开url,虽然不是在应用程序中的回调)。
其内
使用字符串资源,如:
<string name="links">Here is a link: http://www.stackoverflow.com</string>
然后在textview中:
TextView textView = ...
textView.setText(R.string.links);
Linkify.addLinks(textView, Linkify.ALL);
Html
使用Html.fromHtml:
<string name="html">Here you can put html <a href="http://www.stackoverflow.com">Link!</></string>
然后在你的textview中:
textView.setText(Html.fromHtml(getString(R.string.html)));
你可以用这些属性在xml中设置点击处理程序:
android:onClick="onClick"
android:clickable="true"
不要忘记clickable属性,没有它,就不会调用click处理程序。
main。xml
...
<TextView
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:textSize="55sp"
android:onClick="onClick"
android:clickable="true"/>
...
MyActivity.java
public class MyActivity extends Activity {
public void onClick(View v) {
...
}
}
在textView
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:onClick="onClick"
android:clickable="true"
您还必须实现View。OnClickListener和OnClick方法可以使用意图
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://youraddress.com"));
startActivity(intent);
我测试这个解决方案工作良好。
虽然您可以通过将侦听器设置为textview来解决这个问题,但建议不要这样做。你应该使用平面按钮,因为它是按钮的子类,它提供了许多属性,TextView不。
要使用平面按钮,添加style="? "android:attr/borderlessButtonStyle属性-
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DONE"
style="?android:attr/borderlessButtonStyle"/>
这可能不是你想要的,但这是我正在做的事情。所有这些都在onCreate之后:
boilingpointK = (TextView) findViewById(R.id.boilingpointK);
boilingpointK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ("Boiling Point K".equals(boilingpointK.getText().toString()))
boilingpointK.setText("2792");
else if ("2792".equals(boilingpointK.getText().toString()))
boilingpointK.setText("Boiling Point K");
}
});