How to implement OnClickListener on Android

48,477

Try this:

public class MainActivity extends Activity  {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
            .add(R.id.container, new PlaceholderFragment()).commit();
    }

    //Button button = (Button)findViewById(R.id.try_button);      
    //button.setOnClickListener(this);
}

/**
public void onClick(View v) {

}
*/

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment implements OnClickListener {

public PlaceholderFragment() {
}

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

  Button button = (Button) rootView.findViewById(R.id.try_button);      
  button.setOnClickListener(this);

    return rootView;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(getActivity(), "I'm clicked!", Toast.LENGTH_SHORT).show();
}

}
}
Share:
48,477
Bamqf
Author by

Bamqf

Updated on December 05, 2020

Comments

  • Bamqf
    Bamqf over 3 years

    I learn from

    http://developer.android.com/reference/android/widget/Button.html
    

    that "instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute."

    However, I can only get it done with the XML approach, my Listener approach, specified by the following, leads to app crash.

    In my fragment_main.xml:

    <RelativeLayout 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"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.myapp.MainActivity$PlaceholderFragment" >
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
        <Button
            android:id="@+id/try_button" 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text = "TryButton"
            android:onClick="onClick"
        />
    </RelativeLayout>
    

    In my activity_main.xml:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.myapp.MainActivity"
        tools:ignore="MergeRootFrame">
    </FrameLayout>
    

    And in my MainActivity.java:

    public class MainActivity extends Activity implements OnClickListener{
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    
        Button button = (Button)findViewById(R.id.try_button);      
        button.setOnClickListener(this);
    }
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(), "I'm clicked!", Toast.LENGTH_SHORT).show();;
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
    
        public PlaceholderFragment() {
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }
    

    }

    The LogCat says:

    05-20 19:56:17.604: E/MoreInfoHPW_ViewGroup(566): Parent view is not a TextView
    05-20 19:56:17.649: D/AndroidRuntime(566): Shutting down VM
    05-20 19:56:17.649: W/dalvikvm(566): threadid=1: thread exiting with uncaught exception (group=0x4194ec08)
    05-20 19:56:17.654: E/AndroidRuntime(566): FATAL EXCEPTION: main
    05-20 19:56:17.654: E/AndroidRuntime(566): Process: com.example.myapp, PID: 566
    05-20 19:56:17.654: E/AndroidRuntime(566): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MainActivity}: java.lang.NullPointerException
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2328)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2386)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.app.ActivityThread.access$900(ActivityThread.java:169)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.os.Handler.dispatchMessage(Handler.java:102)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.os.Looper.loop(Looper.java:136)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.app.ActivityThread.main(ActivityThread.java:5476)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at java.lang.reflect.Method.invokeNative(Native Method)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at java.lang.reflect.Method.invoke(Method.java:515)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at dalvik.system.NativeStart.main(Native Method)
    05-20 19:56:17.654: E/AndroidRuntime(566): Caused by: java.lang.NullPointerException
    05-20 19:56:17.654: E/AndroidRuntime(566):  at com.example.myapp.MainActivity.onCreate(MainActivity.java:29)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.app.Activity.performCreate(Activity.java:5473)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    05-20 19:56:17.654: E/AndroidRuntime(566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
    05-20 19:56:17.654: E/AndroidRuntime(566):  ... 11 more
    

    I'm using latest Eclipse ADT v22.6.2 on Windows 7, running on Samsung Galaxy Note 10.1 2014.

    What's wrong with my code?

  • Bamqf
    Bamqf almost 10 years
    That would be the xml-only approach, I know it works. But I need to learn the Listener approach.
  • Bamqf
    Bamqf almost 10 years
    Thank you for your answer, but I tried and got similar crash log(with and without the onClick xml attribute). I've edited my post with the complete contents of my files, maybe it would help.
  • dorukayhan
    dorukayhan almost 8 years
    You could make this answer better by explaining how it works.