根据选择的Spinner项目调用不同的方法 - Android

时间:2013-03-30 16:46:44

标签: java android xml

我一直在关注如何使用Spinners的this tutorial,但我现在卡住了。

目前,当从微调器中选择一个项目时,会显示一个选项,我想要做的是运行一种方法来设置所选国家的纬度和经度。

通过调用方法“SetLocationJapan”,“设置日本位置”按钮完美地工作。我只想把这个过程放到微调器中,这样每当做出选择时,纬度和经度都会更新。

例如: 如果在旋转器中选择了日本,我想拨打protected void setLocationJapan() 如果法国被选中,我想致电protected void setLocationFrance() 如果选择了印度,我想打电话给protected void setLocationIndia()

所要求的代码:

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class SunriseSunset extends Activity implements OnClickListener {

    public Button getLocation;
    public Button setLocationJapan;
    public TextView LongCoord;
    public TextView LatCoord;
    public double longitude;
    public double latitude;
    public LocationManager lm;
    private Spinner spinner1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sunrisesunset);

        addListenerOnSpinnerItemSelection();

        findViewById(R.id.my_button).setOnClickListener(this);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
                new MyLocationListener());

        setLocationJapan = (Button) findViewById(R.id.SetLocationJapan);
        getLocation = (Button) findViewById(R.id.GetLocation);
        LongCoord = (TextView) findViewById(R.id.LongCoord);
        LatCoord = (TextView) findViewById(R.id.LatCoord);

        getLocation.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // When GetLocation button is clicked the showCurrentLocation
                // function is ran
                showCurrentLocation();
            }

        });

        setLocationJapan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // When SetLocation button is clicked the setCurrentLocation
                // function is ran
                setLocationJapan();
            }

        });
    }

    public void addListenerOnSpinnerItemSelection() {
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
    }

    protected void setLocationJapan() {
        // TODO Auto-generated method stub
        LatCoord.setText("35.4112");
        LongCoord.setText("135.8337");
    }

    protected void setLocationFrance() {
        // TODO Auto-generated method stub
        LatCoord.setText("65.4112");
        LongCoord.setText("85.8337");
    }

    protected void setLocationIndia() {
        // TODO Auto-generated method stub
        LatCoord.setText("21.4112");
        LongCoord.setText("105.8337");
    }

    protected void showCurrentLocation() {
        // TODO Auto-generated method stub
        // This is called to find current location based on GPS data and sends
        // this to LongCoord and LatCoord TextViewsw
        Location location = lm
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        LongCoord.setText(Double.toString(longitude));
        LatCoord.setText(Double.toString(latitude));
    }

    @Override
    public void onClick(View arg0) {
        Button b = (Button) findViewById(R.id.my_button);
        b.setClickable(false);
        new LongRunningGetIO().execute();
    }

    private class LongRunningGetIO extends AsyncTask<Void, Void, String> {

        protected String getASCIIContentFromEntity(HttpEntity entity)
                throws IllegalStateException, IOException {
            InputStream in = entity.getContent();
            StringBuffer out = new StringBuffer();
            int n = 1;
            while (n > 0) {
                byte[] b = new byte[4096];
                n = in.read(b);
                if (n > 0)
                    out.append(new String(b, 0, n));
            }
            return out.toString();
        }

        @Override
        protected String doInBackground(Void... params) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            // Finds todays date and adds that into the URL
            Calendar c = Calendar.getInstance();
            System.out.println("Current time => " + c.getTime());
            SimpleDateFormat df = new SimpleDateFormat("dd/MM");
            String formattedDate = df.format(c.getTime());

            String finalURL = "http://www.earthtools.org/sun/"
                    + LatCoord.getText().toString().trim() + "/"
                    + LongCoord.getText().toString().trim() + "/"
                    + formattedDate + "/99/0";
            HttpGet httpGet = new HttpGet(finalURL);
            String text = null;

            try {
                HttpResponse response = httpClient.execute(httpGet,
                        localContext);
                HttpEntity entity = response.getEntity();
                text = getASCIIContentFromEntity(entity);
            } catch (Exception e) {
                return e.getLocalizedMessage();
            }
            return text;
        }

        protected void onPostExecute(String results) {
            if (results != null) {
                try {

                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                            .newInstance();
                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                    InputSource s = new InputSource(new StringReader(results));
                    Document doc = dBuilder.parse(s);
                    doc.getDocumentElement().normalize();
                    TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
                    TextView tvSunset = (TextView) findViewById(R.id.Sunset);
                    tvSunrise.setText(doc.getElementsByTagName("sunrise")
                            .item(0).getTextContent());
                    tvSunset.setText(doc.getElementsByTagName("sunset").item(0)
                            .getTextContent());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Button b = (Button) findViewById(R.id.my_button);
            b.setClickable(true);
        }
    }

    class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }   
}

CustomOnItemSelectedListener.java

package richgrundy.learnphotography;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    Toast.makeText(parent.getContext(), 
        "You have changed to : " + parent.getItemAtPosition(pos).toString(),
        Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
  }

}

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SunriseSunset" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:entries="@array/country_arrays"
        android:padding="10dp" />

    <LinearLayout
        android:id="@+id/LinearLayout02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="10dp"
            android:text="Date:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/Date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="10dp"
            android:text="Current Date"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/LinearLayout02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="10dp"
            android:text="Location:"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

    <Button
        android:id="@+id/GetLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Find Current Location" />

    <Button
        android:id="@+id/SetLocationJapan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Set Location to Japan" />

    <LinearLayout
        android:id="@+id/LinearLayout02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/LatCoord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp" />

        <TextView
            android:id="@+id/LongCoord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp" />
    </LinearLayout>

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Calculate Sunrise/Sunset Time" />

    <TextView
        android:id="@+id/Sunrise"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00:00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/Sunset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00:00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

非常感谢任何帮助,谢谢!

我很确定我需要在setLocationJapan()课程内移动CustomOnItemSelectedListener等,但不知道如何从那里开始。

我更喜欢伪代码答案,所以如果可能的话,我可以自己解决这个问题:)

1 个答案:

答案 0 :(得分:1)

这有点脏,但您可以将活动传递给CustomOnSelectedListener,然后使用该活动调用这些方法。例如:

public class CustomOnSelectedListener extends implements OnItemSelectedListener {
    Activity mActivity;

    CustomOnSelectedListener(Activity mActivity) {
         this.mActivity = mActivity;
    }

    public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
         Toast.makeText(parent.getContext(), 
              "You have changed to : " + parent.getItemAtPosition(pos).toString(),
              Toast.LENGTH_SHORT).show();
         if (mActivity instanceof SunriseSunset) {
             SunriseSunset sunrise = (SunriseSunset) mActivity;
             switch (pos) {
                 case 1: // Assuming Japan is first on your list
                     sunrise.setLocationJapan();
                     break;
                 ... // fill in the rest here
             }
         }
    }

... // rest of CustomOnSelectedListener here

}

但是,这意味着您的所有setLocationJapansetLocationIndia等必须从protected更改为public,以便CustomOnSelectedListener可以调用它们。此外,您现在必须像这样实例化CustomOnSelectedListener

spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener(this));