1

Buenas tardes, tengo un pequeño problema con un metodo onClick en un Fragmento

XML

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardBackgroundColor="@android:color/white"
        card_view:cardCornerRadius="4dp"
        card_view:cardElevation="4dp"
        card_view:cardUseCompatPadding="true">

        <LinearLayout
            android:id="@+id/linearLayoutCardContent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/VollyNetworkImageView1"
                android:layout_width="wrap_content"
                android:layout_height="220dp"
                android:adjustViewBounds="true"
                android:src="@drawable/materialdesing"
                android:background="@drawable/materialdesing"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="8dp">


                <TextView
                    android:id="@+id/Tittle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Nombre"
                    android:layout_marginTop="24dp"
                    android:textSize="24dp"/>

                <TextView
                    android:id="@+id/Sub_tittle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Ciudad"
                    android:textSize="14sp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="16dp"/>

                <LinearLayout
                    android:id="@+id/Open_Action"
                    android:clickable="true"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">


                <Button
                    android:id="@+id/Shared"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="8dp"
                    android:text="@string/Button_Shared"/>

                <Button
                    android:id="@+id/Explorar"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="8dp"
                    android:text="@string/Button_Shared"/>

                    <ImageView
                        android:id="@+id/imageViewExpand"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/btn_circle_preseed"
                        android:contentDescription="@string/details"
                        android:src="@drawable/ic_keyboard_arrow_down_black_24dp"
                        android:layout_marginLeft="30dp"
                        android:clickable="true"
                        android:padding="8dp"/>

                </LinearLayout>


            </LinearLayout>


            <LinearLayout
                android:id="@+id/linearLayoutDetails"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingLeft="8dp"
                android:visibility="gone">

                <TextView
                    android:id="@+id/textViewInfo"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/descripcion"
                    android:textColor="@android:color/black"
                    android:textSize="16sp" />
            </LinearLayout>


        </LinearLayout>

    </android.support.v7.widget.CardView>

</ScrollView>

Fragmento

public class TabAttractionGeneral extends Fragment {

List<GetBeach> GetDataAdapter2;

RecyclerView recyclerView;

RecyclerView.LayoutManager recyclerViewlayoutManager;

RecyclerView.Adapter recyclerViewadapter;

TextView time;

String GET_JSON_DATA_HTTP_URL = "http://mextoursvm.southcentralus.cloudapp.azure.com:81/api/App/GetBeaches";

String JSON_BEACHID = "BEACHID";
String JSON_NAME = "NAME";
String JSON_DESCRIPTION = "DESCRIPTION";
String JSON_PLACE = "PLACE";
String JSON_LAT = "LAT";
String JSON_LNG = "LNG";



JsonArrayRequest jsonArrayRequest;

RequestQueue requestQueue;
private ViewGroup linearLayoutDetails;
private ImageView imageViewExpand;
private ImageView open;
private LinearLayout LinearOpen;

private static final int DURATION = 250;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle save){
    View rootView = inflater.inflate(R.layout.tabgeneralbusines, container, false);



    // Bloqear la orientación de pantalla LandScape
    Activity a = getActivity();
    if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);



    GetDataAdapter2 = new ArrayList<>();
    recyclerView = (RecyclerView) rootView.findViewById(R.id.RecyclerGeneralBusines);
    recyclerView.setHasFixedSize(true);
    recyclerViewlayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(recyclerViewlayoutManager);


    JSON_DATA_WEB_CALL();

    linearLayoutDetails = (ViewGroup) rootView.findViewById(R.id.linearLayoutCardContent);
    imageViewExpand = (ImageView) rootView.findViewById(R.id.VollyNetworkImageView1);
    LinearOpen = (LinearLayout) rootView.findViewById(R.id.Open_Action);
    open = (ImageView) rootView.findViewById(R.id.imageViewExpand);
    open.setOnClickListener(new ImageView.OnClickListener() {
        @Override
        public void onClick(View view) {
            toggleDetails(view);
        }
    });








    return rootView;
}



public void JSON_DATA_WEB_CALL(){

    jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,

            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    JSON_PARSE_DATA_AFTER_WEBCALL(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    requestQueue = Volley.newRequestQueue(getActivity());

    requestQueue.add(jsonArrayRequest);
}

public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){

    for(int i = 0; i<array.length(); i++) {

        GetBeach GetDataAdapter = new GetBeach();

        JSONObject json = null;
        try {

            json = array.getJSONObject(i);

            GetDataAdapter.setBEACHID(json.getString(JSON_BEACHID));
            GetDataAdapter.setNAME(json.getString(JSON_NAME));
            GetDataAdapter.setDESCRIPTION(json.getString(JSON_DESCRIPTION));
            GetDataAdapter.setPLACE(json.getString(JSON_PLACE));
            GetDataAdapter.setLAT(json.getString(JSON_LAT));
            GetDataAdapter.setLNG(json.getString(JSON_LNG));


        } catch (JSONException e) {

            e.printStackTrace();
        }
        GetDataAdapter2.add(GetDataAdapter);
    }

    recyclerViewadapter = new RecyclerViewAdapterBeach(GetDataAdapter2, getActivity());

    recyclerView.setAdapter(recyclerViewadapter);
}

public void toggleDetails(View view) {
    if (linearLayoutDetails.getVisibility() == View.GONE) {
        ExpandAndCollapseViewUtil.expand(linearLayoutDetails, DURATION);
        imageViewExpand.setImageResource(R.drawable.ic_keyboard_arrow_down_black_24dp);
        rotate(-180.0f);
    } else {
        ExpandAndCollapseViewUtil.collapse(linearLayoutDetails, DURATION);
        imageViewExpand.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
        rotate(180.0f);
    }
}

private void rotate(float angle) {
    Animation animation = new RotateAnimation(0.0f, angle, Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f);
    animation.setFillAfter(true);
    animation.setDuration(DURATION);
    imageViewExpand.startAnimation(animation);
}

}

Error

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: ixtapa.com.mx.ixtapazihua, PID: 4295
              java.lang.RuntimeException: Unable to start activity ComponentInfo{ixtapa.com.mx.ixtapazihua/ixtapa.com.mx.ixtapazihua.ContentIxtapaActivity}: java.lang.NullPointerException
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
                  at android.app.ActivityThread.access$800(ActivityThread.java:166)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5584)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: java.lang.NullPointerException
                  at ixtapa.com.mx.ixtapazihua.Fragments.TabAttractionGeneral.onCreateView(TabAttractionGeneral.java:101)
                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
                  at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
                  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
                  at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
                  at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
                  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
                  at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:181)
                  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1178)
                  at android.app.Activity.performStart(Activity.java:5452)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2402)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493) 
                  at android.app.ActivityThread.access$800(ActivityThread.java:166) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:136) 
                  at android.app.ActivityThread.main(ActivityThread.java:5584) 
                  at java.lang.reflect.Method.invokeNative(Native Method) 
                  at java.lang.reflect.Method.invoke(Method.java:515)
8
  • ¿Qué activity quieres usar aquí: Activity a = getActivity();?
    – A. Cedano
    Commented el 10 mar. 2017 a las 23:49
  • César ¿puedes clickear en esta parte ` at ixtapa.com.mx.ixtapazihua.Fragments.TabAttractionGeneral.onCreateView(TabAttractionGeneral.java:101)` y señalar que parte de tu código te manda el cursor?
    – x4mp73r
    Commented el 10 mar. 2017 a las 23:55
  • @A.Cedano ahí solo es para que la pantalla no realice un landscape, saludos Commented el 11 mar. 2017 a las 0:14
  • @x4mp73r me lleva directamente a la parte del método. open.setOnClickListener(new ImageView.OnClickListener() { @Override public void onClick(View view) { toggleDetails(view); } }); Commented el 11 mar. 2017 a las 0:16
  • 1
    Es como si tu intentases usar tu fragmento antes de que el mismo esté listo para usar... ¿Qué hay en esta línea: at ixtapa.com.mx.ixtapazihua.Fragments.TabAttractionGeneral.onCreateView(TabAttractionGeneral.java:101), en la línea 101.?
    – A. Cedano
    Commented el 11 mar. 2017 a las 0:24

1 respuesta 1

1

De la forma en que manejas los eventos lo correcto es, por ejemplo:

En las propiedades de tu Imageview

<ImageView  
 ...... 
 android:clickable="true"  
 android:onClick="metodoBonito"  
 .....
 />  

Método el que quieres que maneje:

 public void metodoBonito(View view) {  
  //bla bla bla.....
 }

Por lo tanto, se te ha pasado colocar onClick a tu imageview, el cual le pones el nombre de tu método toggleDetails, entonces quedaría así tu imageView:

               <ImageView
                        android:id="@+id/imageViewExpand"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/btn_circle_preseed"
                        android:contentDescription="@string/details"
                        android:src="@drawable/ic_keyboard_arrow_down_black_24dp"
                        android:layout_marginLeft="30dp"
                        android:clickable="true"
                        android:onClick="toggleDetails"
                        android:padding="8dp"/>

O bien, en lugar de usar ImageView puedes usar ImageButton(El cual yo prefiero) y funciona exactamente como un botón y puedes agregarle el escuhador de eventos de la otra forma, ahí no es necesario colocarle la propiedad onClick ni nada de eso, ejemplo:

  ImageButton imagen = (ImageButton) rootview.findViewById(R.id.imagebutton);
    imagen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mostrarMensaje();
        }
    });

Claro, tiene bordes que le da aspecto de botón pero puedes quitárselo de manera sencilla agregando un color de fondo transparente android:background="@android:color/transparent":

<ImageButton
        android:id="@+id/tuImagen"
        ....
        android:background="@android:color/transparent"
        ..../>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.