How to implement OnClickListener on Android

2020-03-04 09:39发布

问题:

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?

回答1:

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();
}

}
}


回答2:

You don't need implement OnClickListener, because your button execute the method automatically.

Edit:

public class MainActivity extends Activity {

private OnClickListener 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();
    }
    initListener();//Initializing Listener.
    Button button = (Button)findViewById(R.id.try_button);
    //This command causes problem
    button.setOnClickListener(onClickListener);
}

private void initListener(){
         onclickListener = new OnClickListener() {
               @Override
                public void onClick(View view) {
                      Toast.makeText(getApplicationContext(),
                      "Button Clicked",Toast.LENGTH_SHORT).show();
                }
         };
}

Quit the Onclick in your XML.

<Button
        android:id="@+id/try_button" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text = "TryButton"
    />


回答3:

I've explained the different ways you can implement an OnClickListener on my blog: http://www.androiddevresources.com/guides/tutorial-how-to-implement-an-onclicklistener/

Basically there are three ways. - Implement the listener in the activity class (and set the xml attribute) - Create a variable in your activity class (or other class, for example a fragment). - Create a new listener in line with new OnClickListener().

I've added example code in the article and an example project on GitHub which you can download.



回答4:

public class start extends Activity implements View.OnClickListener { Button bSMS;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);
    bSMS = (Button) findViewById(R.id.button);


    bSMS.setOnClickListener(this);

}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub

    switch (arg0.getId()) {

        case R.id.button:        //"Block SMSs" button pressed
            startActivity(new Intent(this,secret_main.class));
            break;

    }
}

}



回答5:

XML : android:onClick="onclickid"

Activity :

public void onclickid(View view)
  {
 //Do something When the button is click
  }

This Should Help, But i suggest to use onclicklistener