Как код для Activity корректно вставить в Fragment?

403
24 мая 2018, 14:40

Проблема в том, чтобы отладить работу контактной формы в Fragment. Нужно сделать, чтобы при нажатии на кнопку формы "Отправить заявку" формировалось сообщение на почту.Так как только начинаю программировать возникли трудности, код для Activity рабочий есть, а вот как его адаптировать под Fragment не знаю. Подскажите пожалуйста неопытному программисту! Заранее большое спасибо!

Работающий код для Activity ContactActivity.java

package com.example.mobile;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ContactActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_form);
        final EditText your_name = (EditText) findViewById (R.id.your_name);
        final EditText your_email = (EditText) findViewById(R.id.your_email);
        final EditText your_gorod = (EditText) findViewById(R.id.your_gorod);
        final EditText your_vuz = (EditText) findViewById(R.id.your_vuz);
        final EditText your_gruppa = (EditText) findViewById(R.id.your_gruppa);
        final EditText your_spec = (EditText) findViewById(R.id.your_spec);
        final EditText your_message = (EditText) findViewById(R.id.your_message);
        Button email = (Button) findViewById(R.id.post_message);
        email.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View view){
                String name = your_name.getText().toString();
                String email = your_email.getText().toString();
                String subject = your_gorod.getText().toString();
                String vuz = your_vuz.getText().toString();
                String grupp = your_gruppa.getText().toString();
                String spec = your_spec.getText().toString();
                String message = your_message.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    your_name.setError("Enter Your Name");
                    your_name.requestFocus();
                    return;
                }
                Boolean onError = false;
                if (!isValidEmail(email)) {
                    onError = true;
                    your_email.setError("Invalid Email");
                    return;
                }
                if (TextUtils.isEmpty(subject)) {
                    your_gorod.setError("Enter Your Subject");
                    your_gorod.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(subject)) {
                    your_vuz.setError("Enter Your Vuz");
                    your_vuz.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(grupp)) {
                    your_gruppa.setError("Enter Your Gruppa");
                    your_gruppa.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(spec)) {
                    your_spec.setError("Enter Your Specialnost");
                    your_spec.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(message)) {
                    your_message.setError("Enter Your Message");
                    your_message.requestFocus();
                    return;
                }

                Intent sendEmail = new Intent(android.content.Intent.ACTION_SEND);
            /* Fill it with Data */
                sendEmail.setType("plain/text");
                sendEmail.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"zencova1996@mail.ru"});
                sendEmail.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
                sendEmail.putExtra(android.content.Intent.EXTRA_TEXT,
                        "Имя:" + name + '\n' + "Email ID:" + email + '\n' + "Сообщение:" + '\n' + message);
            /* Send it off to the Activity-Chooser */
                startActivity(Intent.createChooser(sendEmail, "Send mail..."));
            }
        });
    }

//     validating email id
    private boolean isValidEmail(String email) {
        String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}

Сама форма регистрации fragment_registr.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".Registr">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@android:color/white"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="3dp"
            android:weightSum="1">
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="3dp"
                android:text="
 ФИО"
                android:textAllCaps="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp"
                tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
            <EditText
                android:id="@+id/your_name"
                android:layout_width="fill_parent"
                android:layout_height="38dp"
                android:layout_marginBottom="20dp"
                android:inputType="text"
                android:maxLines="1"
                android:textSize="12sp" />
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="3dp"
                android:text="@string/contact_form_email"
                android:textAllCaps="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp"
                tools:ignore="RtlHardcoded,RtlSymmetry" />
            <EditText
                android:id="@+id/your_email"
                android:layout_width="fill_parent"
                android:layout_height="38dp"
                android:layout_marginBottom="20dp"
                android:inputType="textEmailAddress"
                android:textSize="14sp" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="3dp"
                android:text="@string/contact_form_gorod"
                android:textAllCaps="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp"
                tools:ignore="RtlHardcoded,RtlSymmetry" />
            <EditText
                android:id="@+id/your_gorod"
                android:layout_width="fill_parent"
                android:layout_height="38dp"
                android:layout_marginBottom="20dp"
                android:inputType="text"
                android:maxLines="1"
                android:textSize="12sp" />
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="3dp"
                android:text="@string/university"
                android:textAllCaps="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp"
                tools:ignore="RtlHardcoded,RtlSymmetry" />
            <EditText
                android:id="@+id/your_vuz"
                android:layout_width="fill_parent"
                android:layout_height="38dp"
                android:layout_marginBottom="20dp"
                android:inputType="text"
                android:maxLines="1"
                android:textSize="12sp" />
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="3dp"
                android:text="@string/contact_form_gruppa"
                android:textAllCaps="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp"
                tools:ignore="RtlHardcoded,RtlSymmetry" />
            <EditText
                android:id="@+id/your_gruppa"
                android:layout_width="fill_parent"
                android:layout_height="38dp"
                android:layout_marginBottom="20dp"
                android:inputType="text"
                android:maxLines="1"
                android:textSize="12sp" />
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="3dp"
                android:text="@string/contact_form_spec"
                android:textAllCaps="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp"
                tools:ignore="RtlHardcoded,RtlSymmetry" />
            <EditText
                android:id="@+id/your_spec"
                android:layout_width="fill_parent"
                android:layout_height="38dp"
                android:layout_marginBottom="20dp"
                android:inputType="text"
                android:maxLines="1"
                android:textSize="12sp" />
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="32dp"
                android:paddingLeft="3dp"
                android:text="@string/contact_form_message"
                android:textAllCaps="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp"
                tools:ignore="RtlHardcoded,RtlSymmetry" />
            <EditText
                android:id="@+id/your_message"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:height="5dp"
                android:gravity="top"
                android:inputType="text"
                android:textSize="12sp" />
            <Button
                android:id="@+id/post_message"
                android:layout_width="200dp"
                android:layout_height="25dp"
                android:layout_gravity="center"
                android:layout_weight="0.13"
                android:background="@color/colorPrimary"
                android:paddingBottom="1dp"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:paddingTop="1dp"
                android:text="@string/contact_form_button"
                android:textAllCaps="true"
                android:textColor="@android:color/white"
                android:textSize="12sp" />
        </LinearLayout>
    </ScrollView>
</android.support.design.widget.CoordinatorLayout>

Код имеющегося Fragment Registr.java, в который нужно верно добавить имеющийся выше код

package com.example.mobile;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link Registr.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Registr#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Registr extends Fragment {
    //TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Glavn.OnFragmentInteractionListener mListener;
    public Registr() {
        // Required empty public constructor
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Registr.
     */
    // TODO: Rename and change types and number of parameters
    public static Registr newInstance(String param1, String param2) {
        Registr fragment = new Registr();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_registr, container, false);
    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
      public void onAttach(Context context) {
        super.onAttach(context);
    }
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

     /**
      * This interface must be implemented by activities that contain this
      * fragment to allow an interaction in this fragment to be communicated
      * to the activity and potentially other fragments contained in that
      * activity.
      * <p>
       * See the Android Training lesson <a href=
      * "http://developer.android.com/training/basics/fragments/communicating.html"
      * >Communicating with Other Fragments</a> for more information.
      */
    public interface OnFragmentInteractionListener {
          // TODO: Update argument type and name
       void onFragmentInteraction(Uri uri);
    }
}
Answer 1

Из Activity   положите логику во  Fragment а именно в метом OnCreateView Там где нужно контекст в Fragment-e есть метод getContext();

Оффицальная документация по фрагментам -офф доки

А здесь более внятно - советую поюзать сперва эту доку а потом через определенное время вернуться на Офф доки

READ ALSO
NavController с sharedElementTransition

NavController с sharedElementTransition

В презентации google i/o 2018 анонсировали интересную фичу NavController, я понимаю что фиче всего несколько дней, но может кто-то сталкивался как связать...

217
Jar файл не видит изображение

Jar файл не видит изображение

написал простенький проект в котором есть изображенияПосле чего с архивировал его в jar файл с помощью IntelliJ IDEA

249
Как достать объект через hibernate по его полю, а не по id?

Как достать объект через hibernate по его полю, а не по id?

Собственно мне нужно вытащить автора книг по его имени а не по id

242