How to open the virtual keyboard in a fragment with focus on editText?

0

Hello, I'm developing an application and loading the screen to register the focus is in an editText but I need to automatically load the Android virtual keyboard.

public class AddHerosFragment extends Fragment
    implements TextView.OnEditorActionListener{

    private static final int CODE_GET_REQUEST = 1024;
    private static final int CODE_POST_REQUEST = 1025;

    //Variaveis dos componentes
    EditText editTextHeroId, editTextName, editTextRealname;
    RatingBar ratingBar;
    Spinner spinnerTeam;
    Button buttonAddHero, buttonVoltar;

    ProgressBar progressBarAdd;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_add_hero, container, false);

        //Pegando referencia dos componentes
        editTextHeroId = (EditText) rootView.findViewById(R.id.editTextHeroId);
        editTextName = (EditText) rootView.findViewById(R.id.editTextName);
        editTextName.requestFocus();
        editTextRealname = (EditText) rootView.findViewById(R.id.editTextRealname);
        editTextRealname.setOnEditorActionListener(this);
        ratingBar = (RatingBar) rootView.findViewById(R.id.ratingBar);
        spinnerTeam = (Spinner) rootView.findViewById(R.id.spinnerTeamAffiliation);

        progressBarAdd = (ProgressBar) rootView.findViewById(R.id.progressBarAdd);
        buttonAddHero = (Button) rootView.findViewById(R.id.buttonAddHero);
        buttonVoltar = (Button) rootView.findViewById(R.id.buttonVoltar);

        //Abre o teclado virtual ao exibir o fragment para inserir um novo hero


        return rootView;
    }

    //Usado para manter a instancia do fragment ao minimizar ou girar a tela
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

    }


    @Override
    public void onStart() {
        super.onStart();

        buttonAddHero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createHero();
            }
        });

        buttonVoltar.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                chamaFragmentHero();
            }
        });
    }

    private void createHero() {
        String name = editTextName.getText().toString().trim();
        String realname = editTextRealname.getText().toString().trim();

        int rating = (int) ratingBar.getRating();

        String team = spinnerTeam.getSelectedItem().toString();


        //validação dos campos de nome e nome real
        if (TextUtils.isEmpty(name)) {
            editTextName.setError("Por favor informe o nome");
            editTextName.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(realname)) {
            editTextRealname.setError("Por favor informe seu nome real");
            editTextRealname.requestFocus();
            return;
        }

        //se a validação for ok, ou seja, com campos preenchidos

        HashMap<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("realname", realname);
        params.put("rating", String.valueOf(rating));
        params.put("teamaffiliation", team);


        //Chama o create hero API
        PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_CREATE_HERO, params, CODE_POST_REQUEST);
        request.execute();
        Toast.makeText(this.getActivity(), "Dados inseridos com sucesso", Toast.LENGTH_SHORT).show();
        chamaFragmentHero();
    }

    //classe interna para executar solicitação de rede estendendo um AsyncTask
    private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {

        //o URL onde precisa enviar a solicitação
        String url;

        //Os parametros
        HashMap<String, String> params;

        //O código do pedido para definir se é um GET ou POST
        int requestCode;

        //Construtor para inicializar os valores
        PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
            this.url = url;
            this.params = params;
            this.requestCode = requestCode;
        }

        //Quando a tarefa começou a exibir uma barra de progresso
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBarAdd.setVisibility(View.VISIBLE);
        }

        //Este método dará a resposta do pedido
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressBarAdd.setVisibility(GONE);
            try {
                JSONObject object = new JSONObject(s);
                if (!object.getBoolean("error")) {
                    //Toast.makeText(getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
                    //atualizando o herolista após cada operação
                    //então nós conseguimos uma lista atualizada
                    //refreshHeroList(object.getJSONArray("heroes"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //A operação da rede será realizada em segundo plano
        @Override
        protected String doInBackground(Void... voids) {
            RequestHandler requestHandler = new RequestHandler();

            if (requestCode == CODE_POST_REQUEST)
                return requestHandler.sendPostRequest(url, params);


            if (requestCode == CODE_GET_REQUEST)
                return requestHandler.sendGetRequest(url);

            return null;
        }
    }

    public void chamaFragmentHero(){
        FragmentManager manager = getFragmentManager();
        HerosFragment herosFragment = new HerosFragment();

        manager.beginTransaction().replace(R.id.main_layout, herosFragment).commit();
       // Intent it = new Intent(this.getActivity(), MainActivity.class);
       // startActivity(it);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if (EditorInfo.IME_ACTION_DONE == actionId){
            createHero();
            return true;
        }
        return false;
    }
}
    
asked by anonymous 30.01.2018 / 01:54

1 answer

2

In case I use in an activity

private void mostraTeclado() {
    View v = this.getCurrentFocus();

    if (v != null) {

        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }
}
    
31.01.2018 / 14:56