简体   繁体   中英

Can't set onclicklistener for button after updating ADT

I am really frustrated after updating my ADT. Previously a new Android project only include activity_main.xml file in which we add elements of our interface. Now after updating the ADT whenever I create a new android project it creates a fragment_main.xml along with activity_main.xml file. What is this fragment_main.xml ? Also MainActivity.class includes some extra code like a class named PlaceholderFragment and some other weird stuff.

Now the main problem is I can't even add onClickListener for a button in fragment_main.xml .

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.cameraproject.MainActivity$PlaceholderFragment" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="188dp"
        android:text="Button" />

</RelativeLayout>

MainActivity.class :

package com.example.cameraproject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener {
    public static Button b;

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

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

        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(this);
    }

    @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;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            Toast.makeText(this, "Its working", Toast.LENGTH_SHORT).show();
            break;
        }
    }

}

Error log :

04-22 11:16:54.186: E/AndroidRuntime(17336): FATAL EXCEPTION: main
04-22 11:16:54.186: E/AndroidRuntime(17336): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cameraproject/com.example.cameraproject.MainActivity}: java.lang.NullPointerException
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.access$700(ActivityThread.java:168)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.os.Looper.loop(Looper.java:137)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.main(ActivityThread.java:5493)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at java.lang.reflect.Method.invokeNative(Native Method)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at java.lang.reflect.Method.invoke(Method.java:525)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at dalvik.system.NativeStart.main(Native Method)
04-22 11:16:54.186: E/AndroidRuntime(17336): Caused by: java.lang.NullPointerException
04-22 11:16:54.186: E/AndroidRuntime(17336):    at com.example.cameraproject.MainActivity.onCreate(MainActivity.java:28)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.Activity.performCreate(Activity.java:5372)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)

Try this..

Your Button is belongs to fragment_main.xml So you have to initialize it in PlaceholderFragment

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }
    Button b;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "Its working", Toast.LENGTH_SHORT).show();
        }
    });
        return rootView;
    }
}

You have set the layout file as activity_main.xml ..But you have added the button in fragment_main.xml ..That is why the null pointer exception is raised..

Replace this

setContentView(R.layout.activity_main);

with

setContentView(R.layout.fragment_main);

This is the most simple solution...

OR

Copy the whole contents in fragment_main.xml to activity_main.xml ...

Hope it helps..

Reaplace this line

setContentView(R.layout.activity_main);

by setContentView(R.layout.fragment_main);

Your Button belongs to fragment's layout not your activiti's layout. Hence, remove button view initialization code from your activitie's onCreate() and add,

View rootView = inflater.inflate(R.layout.fragment_main, container, false); Button b = (Button) rootView.findViewById(R.id.button1);

in onCreateView() of your PlaceholderFragment .

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