我有一个可以填写的编辑文本表单,我想在文本的 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/