0

I would like to add a button click event to my code for an Android app.

This is my code:

package com.example.myapplication;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });
    }

    public void button1_Click(View view)
    {
        EditText editTextNumber = (EditText)findViewById(R.id.editTextNumber);
    }
}

It says that findViewById is undefined. How can I fix this?

Thanks for all of your help. It is working fine.

1 Answers1

1

You can change the text of your textbox with a button click using the setText method:

public void onBtnChangeText(View view) {
    EditText editText = (EditText)findViewById(R.id.simpleEditText);
    editText.setText("New text");
}

My xml file is:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0390FF"
        android:onClick="onBtnChangeText"
        android:text="Click to change text"
        android:textAllCaps="false"
        android:textSize="20sp" />

<EditText
        android:id="@+id/simpleEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Old text"
        android:gravity="center"/>

The text will be changed from "Old text" to "New text" when click the button:

Old text

New text

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
  • Could you please share the code and error infomation in your post? – zhangxaochen Jan 21 '21 at 01:48
  • I posted the java file I am having problems with. The error is "Cannot resolve method 'findViewById' in FirsFragment." – Alexander123 Jan 21 '21 at 02:07
  • Haha, that's because ```findViewById``` is called directly while the class extends fragment, you can put the button1_Click method in your activity class or refer to this link about using findViewById in Fragment: https://stackoverflow.com/questions/6495898/findviewbyid-in-fragment – zhangxaochen Jan 21 '21 at 02:09