我有以下代码,我需要填写if(pos == 1){??????????}
,以便我可以在选择我的微调器中的第一个位置时切换活动。我的新活动的名称是Route1.java。
在我的微调器中选择位置1时,如何编写代码以切换到Route1.java。
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.Manifest.permission;
public class MyOnItemSelectedListener extends Activity
implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if (pos == 1) {
} else {
Toast.makeText(parent.getContext(),
"Your route is "
+ parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
上述类用于此类
import java.lang.reflect.Array;
import android.R.array;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.AbsSpinner;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class cnycentro extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cnycentro);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.routes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
}
答案 0 :(得分:0)
你应该阅读意图,更具体地说是明确的意图。
为了显式启动新活动(如您创建的活动),语法为:
Intent newActivity = new Intent(this, Route1.class);
startActivity(newActivity);
还要确保将新活动添加到android清单中:
<activity android:name=".Route1"></activity>
编辑:
+1表示不在您的侦听器中扩展Activity,而只是写
public class MyOnItemSelectedListener implements OnItemSelectedListener {
....
}
如果您的Activity或Listener太大而且会降低内联编写的可读性,您可以这样写。
答案 1 :(得分:0)
将您的代码更改为以下内容:
OnItemSelectedListener listener = new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
//do you really want 1 here or 0?
if (position == 1) {
view.getContext().startActivity(new Intent(view.getContext().getApplicationContext(),Route1.class));
}else{
Toast.makeText(parent.getContext(), "Your route is " +
parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
spinner.setOnItemSelectedListener(listener);