Android onClick 函数用于编辑文本,如何调用编辑文本?

标签 android onclick android-edittext

我有一个可以填写的编辑文本表单,我想在文本的 onClick 上清除它,所以我在 main 中放置了一个转到我的清除函数的 onClick 。

但是,我不知道如何正确定位我想要的编辑文本。我想清除其中两个。

public void clear(View v) {
    @+id/toptext.setText("");

} 

这是该特定文本的 XML。

<TextView
android:id="@+id/toptext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#303030"
android:text="@string/toptext"
android:textAppearance="?
android:attr/textAppearanceLarge"
android:textColor="#33B5E5"
android:textSize="50sp"
android:onClick="clear"  />

最佳答案

使用 xml 布局中 EditText 的 id 创建 EditText 的实例。然后对它们使用 setText 并将其设为空白。

public void clear(View v) {

    EditText et = (EditText)findViewById(R.id.theIdOfYourEditText);
    EditText et2 = (EditText)findViewById(R.id.theIdOfYourOtherEditText);
    et.setText("");
    et2.setText("");
} 

编辑由于某种原因,上述方法不起作用。这是最终的解决方案:

// Put one of these in your onCreate method:

TextView tt = (TextView)findViewById(R.id.toptext);
tt.setOnTouchListener(new View.OnTouchListener() { 
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        EditText et = (EditText)findViewById(R.id.theIdOfYourEditText);
        EditText et2 = (EditText)findViewById(R.id.theIdOfYourOtherEditText);
        et.setText("");
        et2.setText("");

        return true;
    }
});

// or

TextView tt = (TextView)findViewById(R.id.toptext);
tt.setOnClickListener(new View.OnClickListener() { 
    @Override
    public void onClick(View v) {

        EditText et = (EditText)findViewById(R.id.theIdOfYourEditText);
        EditText et2 = (EditText)findViewById(R.id.theIdOfYourOtherEditText);
        et.setText("");
        et2.setText("");
    }
});

关于Android onClick 函数用于编辑文本,如何调用编辑文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21194588/

相关文章:

android - 读取和写入外部存储权限不起作用

java - 如何将 String[] 传递给 JAVA 中接受 String 的方法

android - Firebase Spark 计划云消息传递限制

android - 自定义通知中按钮的事件 OnClick

jquery - 将 .live ("click"与彼此内部的元素一起使用时,如何仅引用一个元素?

android - 如何让 TextWatcher 在执行某些操作之前等待一段时间

android - 错误 : Could not find or load main class com. android.uiautomator.UiAutomatorViewer

javascript - Oclick Javascript 函数不工作

android - 使用 AppCompat 的 Material 设计反向微调器/编辑文本主题

android - 自定义 EditText 的错误状态