gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:34:21 24 4
gpt4 key购买 nike

我一直在看this tutorial了解如何使用微调器,但我现在卡住了。

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

“将位置设置为日本”按钮通过调用“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>

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

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

我更喜欢伪代码答案,这样我就可以自己解决这个问题 :)

最佳答案

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

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));

关于java - 根据选择的 Spinner 项目调用不同的方法 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15720977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com