简体   繁体   中英

onclicklistener doesn't work on fragment - android studio

Greeting When I click on TextView on the fragment, the app is crash. Please I need the expertise to help me to fix it. I have read many in the internet but no solution yet and I try many ways and all are not able to solve mine

package com.example.mymahine.nav1;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.VelocityTrackerCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;


/**
 * A simple {@link Fragment} subclass.
 */
public class CameraFragment extends Fragment implements onClickListener{
private TextView textView;
    public CameraFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_camera, container, false);
        TextView textview = (TextView) view.findViewById(R.id.frag_text);
        textview.setOnClickListener(new onClickListener);
        // Inflate the layout for this fragment

        return view;


    }

    @Override
    public void onClick(View v){
        Intent intent = new Intent(getActivity(), Main2Activity.class);
        startActivity(intent);
    }

/*
    public void onActivityCreated(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);


        TextView tv2 = (TextView) getActivity().findViewById(R.id.textView1);
        tv2.setOnClickListener(new view2.OnClickListener() {
            public void onClick(View v) {

                Intent intent = new Intent(getActivity(), Main2Activity.class);
                startActivity(intent);
                }
             }
        );

    }
*/

}

Below is logcat:

06-01 13:14:28.607 4559-4559/com.example.mymachine.nav1 D/AndroidRuntime: Shutting down VM 06-01 13:14:28.608 4559-4559/com.example.mymachine.nav1 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.mymachine.nav1, PID: 4559 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mymachine.nav1/com.example.mymachine.nav1.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke( Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference at com.example.mymachine.nav1.Main2Activity.onCreate(Main2Activity.java:17) at android.app.Activity.performCreate(Activity.java:6679) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.r eflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

fragment_camera.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.shakeralmoosa.nav1.CameraFragment">

<!-- TODO: Update blank fragment layout -->

<TextView
    android:id="@+id/frag_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="195dp"
    android:text="GO TO NEXT ACTIVITY"
    android:textAlignment="center"
    android:textSize="30sp"
    android:clickable="true"
    android:onClick="onClick"
    android:focusable="true"
    android:focusableInTouchMode="true"/>
    </LinearLayout>
1    Replace your code with this:

    public class CameraFragment extends Fragment implements View.OnClickListener{
    public CameraFragment() {
        // Required empty public constructor
    }

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_camera, container, false);
    TextView textview = (TextView) view.findViewById(R.id.frag_text);
    textView.setOnClickListener(this);
    return view;
}

@Override
    public void onClick(View v){
        Intent intent = new Intent(getActivity(), Main2Activity.class);
        startActivity(intent);
    }

Try this if it helps,

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_camera, container, false);
        TextView textview = (TextView) view.findViewById(R.id.frag_text);
        textview.setOnClickListener(this);
        // Inflate the layout for this fragment

        return view;


    }

      @Override
    public void onClick(View v) {
     switch(v.getId()){

     case R.id.frag_text :
         //your code...
         Intent intent = new Intent(getActivity(), Main2Activity.class);
         startActivity(intent);
     break;

    default:
        break;

     }

    }

check below code:

 public class CameraFragment extends Fragment implements View.OnClickListener{
        private TextView textView;
        public CameraFragment() {
            // Required empty public constructor
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_camera, container, false);
            TextView textview = (TextView) view.findViewById(R.id.frag_text);
            textview.setOnClickListener(this);
            // Inflate the layout for this fragment
            return view;
        }
        @Override
        public void onClick(View v){
            Intent intent = new Intent(getActivity(), Main2Activity.class);
            startActivity(intent);
        }


    }

You can set the click handler in xml(For your Textview) :

android:onClick="onClick" android:clickable="true"

In your Activity:

public class yourActivity extends Activity {

          public void onClick(View v) {
            ...
          }  
       }

Finally, I have resolved the problem

Last error was Nullpointer & can't activity started

I go to main2activity.java and do the followings:

1- remove

private TextView textview;
private View view;

change the following

textView = (TextView) view.findViewById(R.id.textView2);

to

TextView textView = (TextView) findViewById(R.id.textView2);

My app is working fine now.

Thanks for everybody who borrow me his time to help me. See you in another problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM