由于onClickListener而崩溃

时间:2014-11-23 07:00:54

标签: android onclicklistener

http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

初学者android dev在这里。 我目前正在按照本指南尝试创建一个返回用户位置的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的东西,我的应用程序运行正常,所以我知道问题就在于此。我只是不确定它在启动时崩溃了我的应用程序。

3 个答案:

答案 0 :(得分:0)

您已使用过两者

         setOnClickListener in class 

         android:onClick="sendLocation"  in your xml 

使用任何一个。

答案 1 :(得分:0)

删除该行:

android:onClick="sendLocation"

来自您的xml,写在Button标签

答案 2 :(得分:0)

是的,碎片是一个棘手的事情。将片段添加到活动时,它不会立即添加片段。您正在添加片段,然后立即尝试查找片段内的按钮。不幸的是,按钮不在您的视图层次结构中。因此,您的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字段从您的活动移动到您的片段。当您使用片段时,您的活动往往变得非常简单,并且大多数逻辑都可以存在于片段中。