I am trying to get user input using EditText from fragment after pressing a button. For some reason the button is clickable but no data from EditText.
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/txtUserInput"/>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnTest"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"/>
public class MainActivity extends AppCompatActivity {
TestFragment testFragment = new TestFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, testFragment)
.commit();
}
}
public class TestFragment extends Fragment {
Button btnTest;
EditText txtUserInput;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
btnTest = view.findViewById(R.id.btnTest);
txtUserInput = view.findViewById(R.id.txtUserInput);
String input = txtUserInput.getText().toString();
btnTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), input, Toast.LENGTH_LONG).show();
}
});
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
2
Answers
Add gettext() inside your click listener
as you want data from edite text after clicking the button so once you click then on click event is triggered and then you should get data from edit field
you can do this thing like
and View is used to get root view for the fragment.