如何点击或轻触 TextView 文本

216

我知道这很简单(呃……),但我正在寻找一种在Android应用程序中点击或轻触TextView文本行时运行方法的方法。

我一直在考虑按钮监听器和匿名方法监听器调用,但似乎并不适用于TextView。

有人可以指向一些代码片段,以显示如何在TextView上点击或轻触文本块时运行方法吗?


69
你应该真正接受最佳答案。 - Marek Sebera
8
他需要登录才能这样做。 - Carl Anderson
16
他还拿走了一个好的用户名 :/ - MeetM
将来,如果有人正在使用 Kotlin 并希望完全控制可点击文本并进行回调 - 我写了一篇关于为 TextView 编写扩展函数的文章 - https://link.medium.com/TLq6s8ltc3 - Hossain Khan
8个回答

473

您可以使用以下属性在xml中设置点击处理程序:

android:onClick="onClick"
android:clickable="true"

不要忘记 clickable 属性,如果没有它,点击处理程序将不会被调用。

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) {
            ...
          }  
       }

63
别忘了添加 clickable 属性,没有它,点击事件处理程序就不会被调用。这一行代码拯救了我的一天。非常感谢你,伙计。 - N-JOY
2
http://developer.android.com/reference/android/view/View.html#attr_android:onClick 需要提到可点击性(clickable)。如果有提到,就可以节省一小时的时间了。 - taylor
5
有趣的是,使用setOnClickListener会设置clickable属性,但是使用onClick属性似乎不会。 - njzk2
5
在Android 5.0 Lollipop(API 21)中,似乎onClick确实设置了clickable属性。也许他们认为在旧版本中未发生这种情况是一个错误? - Mark Doliner
1
同时最好也将 android:focusable = true 设置为真。 - Amin Guermazi
显示剩余4条评论

56

这可能不完全是你想要的,但这是我正在做的事情所使用的方法。以下都是在我的 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");
    }
});

27

好的,我已经回答了自己的问题(但这是最好的方法吗?)

在TextView上单击或点击某些文本时,这是运行方法的方法:

package com.textviewy;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class TextyView extends Activity implements OnClickListener {

TextView t ;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    t = (TextView)findViewById(R.id.TextView01);
    t.setOnClickListener(this);
}

public void onClick(View arg0) {
    t.setText("My text on click");  
    }
}

我的main.xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content"             android:layout_height="wrap_content"></LinearLayout>
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content"   android:layout_height="wrap_content"></ListView>
<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content"   android:layout_height="wrap_content"></LinearLayout>

<TextView android:text="This is my first text"
 android:id="@+id/TextView01" 
 android:layout_width="wrap_content" 
 android:textStyle="bold"
 android:textSize="28dip"
 android:editable = "true"
 android:clickable="true"
 android:layout_height="wrap_content">
 </TextView>
 </LinearLayout>

13

在调用布局和文本视图的活动内,此单击侦听器有效:

setContentView(R.layout.your_layout);
TextView tvGmail = (TextView) findViewById(R.id.tvGmail);
String TAG = "yourLogCatTag";
tvGmail.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View viewIn) {
                try {
                    Log.d(TAG,"GMAIL account selected");
                } catch (Exception except) {
                    Log.e(TAG,"Ooops GMAIL account selection problem "+except.getMessage());
                }
            }
        });

文本视图的声明方式如下(默认向导):

        <TextView
            android:id="@+id/tvGmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/menu_id_google"
            android:textSize="30sp" />

并且在strings.xml文件中

<string name="menu_id_google">Google ID (Gmail)</string>

12

虽然你可以通过将监听器设置为TextView来解决问题,但建议不要这样做。您应该使用平面按钮,因为它是Button的子类,并提供了许多TextView没有的属性。


要使用平面按钮,请添加style="?android:attr/borderlessButtonStyle"属性 -

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="DONE"
    style="?android:attr/borderlessButtonStyle"/>

您可能还想添加 android:textAllCaps="false" 以允许小写文本。 - SqAR.org

9

在TextView中

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:onClick="onClick"
    android:clickable="true"

你还必须实现View.OnClickListener接口,在On Click方法中可以使用意图(Intent)。
    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
           intent.setData(Uri.parse("https://youraddress.com"));    
            startActivity(intent);

我测试了这个解决方案并且表现良好。


4
要点击文本中的一部分(而不是整个 TextView),您可以使用 HtmlLinkify (两者都创建打开 URL 的链接,但不是应用中的回调)。

Linkify

使用字符串资源,例如:

<string name="links">Here is a link: http://www.stackoverflow.com</string>

然后在一个文本视图中:

TextView textView = ...
textView.setText(R.string.links);
Linkify.addLinks(textView, Linkify.ALL);

Html

使用 Html.fromHtml 方法:

<string name="html">Here you can put html &lt;a href="http://www.stackoverflow.com"&gt;Link!&lt;/&gt;</string>

然后在你的TextView中:

textView.setText(Html.fromHtml(getString(R.string.html)));

0
你可以使用TextWatcher来监听TextView的变化,它比ClickLinstener更加灵活(不是更好或更差,只是一种更多的方式)。
holder.bt_foo_ex.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // code during!

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // code before!

        }

        @Override
        public void afterTextChanged(Editable s) {
            // code after!

        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接