Android 由于onclick侦听器而崩溃

Android 由于onclick侦听器而崩溃,android,onclicklistener,Android,Onclicklistener,这里是初学者android开发人员。 我目前正在按照这个指南尝试创建一个返回用户位置的Android应用程序 package com.example.newapp; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import

这里是初学者android开发人员。 我目前正在按照这个指南尝试创建一个返回用户位置的Android应用程序

package com.example.newapp;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
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.ViewGroup;
import android.widget.Button;
import android.widget.Toast;



public class MainActivity extends ActionBarActivity {

    Button btnShowLocation;

    GPSTracker gps;

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

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        //show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //create class object
                gps = new GPSTracker(MainActivity.this);

                //check if GPS enabled
                if (gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                } else{
                    //can't get location
                    gps.showSettingsAlert();
                }
            }
        });
    }


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

    public void sendLocation(View view){
        AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setMessage("Your latitude is " + gps.getLatitude() + " and your longitude is " + gps.getLongitude());
        builder1.setCancelable(true);
        AlertDialog alert1 = builder1.create();
        alert1.show();
    }

}
我的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.newapp.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <EditText android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />

    <Button
        android:id="@+id/btnShowLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="118dp"
        android:text="Button" 
        android:onClick="sendLocation" />

</RelativeLayout>

我已经注释掉了onClickListener的内容,我的应用程序运行良好,所以我知道问题出在这方面。我只是不确定启动时它会使我的应用程序崩溃。你两个都用过了

         setOnClickListener in class 

使用任意一行。

删除该行:

android:onClick="sendLocation"

从你的xml中,写在按钮标签中是的,这是一个有片段的棘手问题。将片段添加到活动时,它不会立即添加片段。您正在添加片段,然后立即尝试查找片段内的按钮。不幸的是,该按钮还不在视图层次结构中。因此,您的btnShowLocation为null,当您尝试在按钮上设置侦听器时,启动时会发生崩溃

您需要做的是在片段代码中配置按钮,而不是在活动代码中配置按钮。无论如何,这是一个合乎逻辑的地方,因为按钮在片段的布局中

试试这个:

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

    // Notice that you have to call findViewById on rootView, NOT the fragment.
    // This is because you are in the process of telling Android about your fragment's 
    // views, but you haven't actually returned the view hierarchy yet
    Button btnShowLocation = (Button) rootView.findViewById(R.id.btnShowLocation);

    //show location button click event
    btnShowLocation.setOnClickListener(new View.OnClickListener() {
        ...
    }
    return rootView;
}

您还必须将gps场从活动向下移动到片段。当您使用片段时,您的活动往往变得非常简单,大部分逻辑都可以存在于片段中。

我遵循了这一点,现在我的应用程序启动了,但当我按下按钮时,它会崩溃。我在onClickListener中输入了“gps=newgpstracker(gps);”以及Toast.makeTest(gps,…);由于其他参数无法处理片段中的代码,所以我使用getActivity()使其正常工作。非常感谢你的帮助!
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    // Notice that you have to call findViewById on rootView, NOT the fragment.
    // This is because you are in the process of telling Android about your fragment's 
    // views, but you haven't actually returned the view hierarchy yet
    Button btnShowLocation = (Button) rootView.findViewById(R.id.btnShowLocation);

    //show location button click event
    btnShowLocation.setOnClickListener(new View.OnClickListener() {
        ...
    }
    return rootView;
}