Come implementare OnClickListener su Android

? Bamqf @ | Original: StackOverFlow
---

I learn from

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

che " invece di applicare una OnClickListener al pulsante nella vostra attività, è possibile assegnare un metodo per il pulsante nel layout XML, utilizzando l'androide : . onclick "

Tuttavia, posso farlo fare solo con l'approccio XML, il mio approccio Listener, specificato dal seguente, porta alla app crash.

Nel mio 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>

Nel mio 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>

E nella mia 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;
    }
}

}

Il logcat dice :

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

Sto utilizzando ultimo Eclipse ADT v22.6.2 su Windows 7, in esecuzione su Samsung Galaxy Note 10.1 2014.

Cosa c'è di sbagliato con il mio codice ?

---

Top 5 Risposta

1user3586222 @

Non è necessario implementare OnClickListener, perché il pulsante eseguire il metodo automatico .

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

Chiudere la Onclick in XML .

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

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

}
}