I want to make a button to clear the TextView text. Im using 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="";
}
});
You have to instantiate the text view:
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=("");
}
});
You forgot to instantiate your views for ImageButton and 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="";
}
});
I would recommend you to name your variables in camel case.
Also if you can choose a more meaningful name it will be better.
You gotta find BOTH your views before you can manipulate them in your code.
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("");
}
});
XML is file code
<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 is file code
txDemo = findViewById(R.id.tx_demo);
btnClear = findViewById(R.id.btnClear);
btnClear.setOnClickListener(v -> {
txDemo.setText("");
});
OR
txDemo = findViewById(R.id.tx_demo)
txDemo = findViewById(R.id.tx_demo)
btnClear = findViewById<MaterialButton>(R.id.btnClear)
btnClear.setOnClickListener(View.OnClickListener { v: View? ->
txDemo!!.text = ""
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.