2

我一直在查看本教程以了解如何使用 Spinners,但我现在被卡住了。

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

通过调用方法“SetLocationJapan”,“Set Location to Japan”按钮可以完美工作。我只想把这个过程放到微调器中,这样每当做出选择时,都会更新纬度和经度。

例如:如果在微调器中选择了日本 我想打电话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但不知道如何从那里开始。

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

4

1 回答 1

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

}

但是,这意味着您的所有setLocationJapan,setLocationIndia等都必须从 更改protectedpublic才能CustomOnSelectedListener调用它们。此外,您现在必须像这样实例化CustomOnSelectedListener

spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener(this));
于 2013-03-30T16:57:56.217 回答