TextView OnClickListener在片段

时间:2018-02-18 04:10:12

标签: android android-fragments

我对Android中的这个片段编码很新,所以我希望这是一个简单的回答。

我有一个TextView对象,' next',点击后,似乎没有响应。单击TextView文本时,我想做一些事情。首先,检查eventName微调器中的String值,然后Toast the eventID值,最后为下一部分用户交互启动一个新片段。

我还没有实现新片段或对片段的调用。我假设调用新片段的方法是使用以下代码:

NextFragment nextFrag= new NextFragment();
     getActivity().getSupportFragmentManager().beginTransaction()
     .replace(R.id.Layout_container, nextFrag,"findThisFragment")
     .addToBackStack(null)
     .commit();

我的问题是:

  1. 为什么Toast没有显示?好像OnCickListener或OnClick方法似乎没有触发Toast。

  2. 上面的代码是否需要做的就是调用新的片段并在当前的Activity中激活它还是需要在Activity代码中添加其他东西?

  3. 片段代码:

    import android.content.Context;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.util.ArrayList;
    
    
    /**
     * A simple {@link Fragment} subclass.
     * Activities that contain this fragment must implement the
     * {@link FindEventFragment.OnFragmentInteractionListener} interface
     * to handle interaction events.
     * Use the {@link FindEventFragment#newInstance} factory method to
     * create an instance of this fragment.
     */
    public class FindEventFragment extends Fragment{
    
        public static final String TAG = "FindEventFragment";
        private VolleyHelper mInstance;
        private ArrayList<String> eventList = new ArrayList<String>();
        private JSONArray result;
        private Spinner eventNameSpinner;
        private TextView eventDate;
        private String eventID;
        private TextView next;
        //TextView errorText;
    
        // 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 OnFragmentInteractionListener mListener;
    
        public FindEventFragment() {
            // 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 FindEventFragment.
         */
        // TODO: Rename and change types and number of parameters
        public static FindEventFragment newInstance(String param1, String param2) {
            FindEventFragment fragment = new FindEventFragment();
            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);
            }
        }
    
        public void onStart() {
            super.onStart();
            // Instantiate the RequestQueue from VolleyHelper
            mInstance = VolleyHelper.getInstance(getActivity().getApplicationContext());
            // API
            connectApi();
        }
    
        @Override
        public void onStop () {
            super.onStop();
            if (mInstance.getRequestQueue() != null) {
                mInstance.getRequestQueue().cancelAll(TAG);
            }
        }
    
        private void connectApi() {
            String url = "http://gblakes.ddns.net/get_events.php";
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String ServerResponse) {
    
                            JSONObject j = null;
                            try {
                                result = new JSONArray(ServerResponse);
                                eventDetails(result);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                           Toast.makeText(getActivity().getApplicationContext(), "Oops, something went wrong", Toast.LENGTH_LONG).show();
                        }
                    });
    
            if (mInstance != null) {
                // Add a request to your RequestQueue.
                mInstance.addToRequestQueue(stringRequest);
                // Start the queue
                mInstance.getRequestQueue().start();
            }
        }
    
        private void eventDetails(JSONArray j) {
            eventList.add("Choose an event");
            for (int i = 0; i < j.length(); i++) {
                try {
                    JSONObject json = j.getJSONObject(i);
                    // eventList.add(json.getString("EventName") + json.getString("EventDate"));
                    eventList.add(json.getString("EventName"));
                } catch (JSONException e) {
                    //e.printStackTrace();
                    Log.d(TAG, e.toString());
                }
            }
    
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, eventList);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            eventNameSpinner.setAdapter(dataAdapter);
    
            eventNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                    //Setting the value to textview for a selected item
                    eventDate.setText(getEventDate(position));
                    eventID = (getEventID(position));
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    eventDate.setText("test me");
                }
            });
            next.setOnClickListener(new View.OnClickListener() {
                @Override
                  public void onClick(View v) {
                    //Make sure the user has made a valid selection
                    //errorText.setError("");
                    if (eventNameSpinner.equals("Choose an event")){
                        //errorText.setError("");
                        Toast.makeText(getActivity().getApplicationContext(),"Choose an event first",Toast.LENGTH_LONG);
                        //errorText.setText("Choose an event first");
                    } else {
                        //if an event is selected then open the next fragment
                        Toast.makeText(getActivity().getApplicationContext(),eventID.toString(),Toast.LENGTH_LONG);
                    }
                }
            });
    
        }
    
        private String getEventID(int position) {
            String eventID = "";
            try {
                //Getting object of given index
                JSONObject json = result.getJSONObject(position);
                //Fetching name from that object
                eventID = json.getString("EventID");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Returning the name
            return eventID;
        }
    
        private String getEventDate(int position){
            String eventDate="";
            try {
                JSONObject json = result.getJSONObject(position);
                eventDate = json.getString("EventDate");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return eventDate;
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View v = inflater.inflate(R.layout.fragment_find_event,container,false);
            eventNameSpinner = (Spinner) v.findViewById(R.id.spinEventPicker);
            //eventNameSpinner = new Spinner(getActivity().getApplicationContext());
    
            eventDate = (TextView) v.findViewById(R.id.textEventDate);
            next = (TextView) v.findViewById(R.id.link_judgeToEvent);
            eventDate.setText("test me");
    //        errorText = (TextView)eventNameSpinner.getSelectedView();
    
            return v;
        }
    
        // TODO: Rename method, update argument and hook method into UI event
        public void onButtonPressed(Uri uri) {
            if (mListener != null) {
                mListener.onFragmentInteraction(eventID);
    
            }
        }
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if (context instanceof OnFragmentInteractionListener) {
                mListener = (OnFragmentInteractionListener) context;
            } else {
                throw new RuntimeException(context.toString()
                        + " must implement OnFragmentInteractionListener");
            }
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
            mListener = null;
        }
    
        public interface OnFragmentInteractionListener {
            // TODO: Update argument type and name
            void onFragmentInteraction(String eventID);
        }
    }
    

    和片段的XML

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:id="@+id/textEventName">
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/spinEventPicker"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:gravity="center"
            android:layout_alignParentStart="true" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Large Text"
            android:id="@+id/textEventDate"
            android:layout_marginTop="49dp"
            android:layout_below="@+id/spinEventPicker"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
        <TextView
            android:id="@+id/link_judgeToEvent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="24dp"
            android:layout_below="@+id/textEventDate"
            android:gravity="center"
            android:text="Next"
            android:textAlignment="center"
            android:textSize="16dip" />
    </RelativeLayout>
    

1 个答案:

答案 0 :(得分:0)

如果你调用show(),

将显示Toast,所以你必须改变以下代码行

 Toast.makeText(getActivity().getApplicationContext(),"Choose an event first",Toast.LENGTH_LONG).show();

您可以使用以下代码示例代码从另一个片段

启动片段
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment1, fragment2);
    fragmentTransaction.commit();