用于清除TextView文本的Android Studio按钮

vyu0f0g1  于 2023-01-11  发布在  Android
关注(0)|答案(4)|浏览(359)

我想做一个按钮来清除文本视图文本。我使用Android Studio。

ImageButton ImageButton3;
TextView TextView26;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageButton3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            TextView.text="";
        }
    });
7cwmlq89

7cwmlq891#

您必须示例化文本视图:

ImageButton ImageButton3;
TextView TextView26;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView26 = (TextView) findViewById(R.id.<your text view id>);

    ImageButton3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            TextView26.setText=("");
        }
    });
nhn9ugyo

nhn9ugyo2#

您忘记示例化ImageButton和TextView的视图。

ImageButton ImageButton3;
TextView TextView26;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageButton3 = (ImageButton) findViewById(R.id.myImgBtnId);
    TextView26 = (TextView) findViewById(R.id.myTvId);

    ImageButton3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            TextView26.text="";
        }
    });
omvjsjqw

omvjsjqw3#

我建议你用 Camel 的名字命名变量。
另外,如果你能选择一个更有意义的名字,它会更好。
你必须找到你的两个视图,然后才能在你的代码中操作它们。

ImageButton imageButton3; //name to clearTextButton?
TextView textView26; 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imageButton3 = (ImageButton) findViewById(R.id.imgButtonId); //replace it with your true id in your xml
    textView26 = (TextView) findViewById(R.id.textViewId);

    imageButton3.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        textView26.setText("");
    }
});
t5fffqht

t5fffqht4#

XML是文件代码

<com.google.android.material.textview.MaterialTextView
    android:id="@+id/tx_demo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Demo World!" />

<com.google.android.material.button.MaterialButton
    android:id="@+id/btnClear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Clear text Button" />

Java是文件代码

txDemo = findViewById(R.id.tx_demo);
    btnClear = findViewById(R.id.btnClear);
    btnClear.setOnClickListener(v -> {
        txDemo.setText("");
    });

txDemo = findViewById(R.id.tx_demo)
    btnClear = findViewById<MaterialButton>(R.id.btnClear)
    btnClear.setOnClickListener(View.OnClickListener { v: View? ->
        txDemo!!.text = ""
    })

相关问题