当用户点击下一个按钮时,我正在尝试根据参数值启动一项新活动
<Button
android:id="@+id/next"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/next" />
我认为我不应该使用我所知道的代码来启动新活动,因为它只会启动一个活动。
android:onClick="lanzarActividad"
我的目的是用户设置一个参数(一个数字),每个数字对应不同的活动。
我想我应该写一些类似的东西(在onCreate方法中)
Button btn=(Button)findViewById(R.id.next);
int parameter=1;
//it already contains a number, in our case, it might be for instance 1
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
switch(parameter)
{
//Now I get the problem.
case 0 :
lanzarCalculate(v);
case 1 :
lanzarCalculate2(v);
}
}
});
创建意图的方法是
public void lanzarCalculate(View view)
//si apretamos el boton calculate
{
Intent i = new Intent(this, Calculate.class);
Bundle b = new Bundle();
b.putDouble("time", tau);
i.putExtras(b);
startActivity(i);
}
public void lanzarCalculate2(View view)
{
Intent i = new Intent(this, Calculate2.class);
Bundle b = new Bundle();
b.putDouble("time", tau);
i.putExtras(b);
startActivity(i);
}
在这里输入代码
非常感谢,我希望你能帮助我。
答案 0 :(得分:1)
我认为您的问题是您不确定如何“动态”使用Intent。这就是我为避免重复代码而采取的措施
@Override
public boolean onMenuItemClick(MenuItem item)
{
Intent intent = new Intent(); // first, create your Intent object
String nextAct = null; // name for Activity to start with Intent
String package = "com.my.package."; // set package name
int flag = -1; // in case you want to set certain flags depending on activity
switch (item.getItemId())
{
case (R.id.logout): // mine are menu options so you will use the ints that you have already
nextAct = package + "LoginScreen";
flag = Intent.FLAG_ACTIVITY_CLEAR_TOP;
break;
case (R.id.changeLocation):
nextAct = package+ "ChangeLocation"; // package is reused but in some cases it different for me
break;
default:
Toast.makeText(getApplicationContext(), "Item currently not available", Toast.LENGTH_SHORT).show();
}
try
{
if (nextAct != null)
{
intent = new Intent(BaseActivity.this, Class.forName(nextAct)); // change the String that I was setting to the Activity name
if (flag != -1)
{ intent.setFlags(flag); } // set my flags if I had any
startActivity(intent); // start the Activity as you normally would
}
这适用于PopupMenu,但您可以在onClick()
中执行相同的操作。我在代码中添加了注释,以帮助解释它的作用。
另外,这个
android:onClick="lanzarActividad"
你的xml会好的。有了这个,您就不需要定义Button
和监听器
public void lanzarActividad(View v)
{
// code from above
}
点击Button
修改强>
在您创建YourActivityName.this
时,您似乎需要使用this
代替Intents
。此外,在每种情况下添加break;
语句,否则它将继续并运行下一个case
。但上面的代码将使您无需重写Intent
代码,因为大多数代码都是相同的
答案 1 :(得分:1)
如果您搜索“开始活动”http://developer.android.com/training/basics/firstapp/starting-activity.html
,则会在文档中很好地解释这一点基本上您需要创建Intent
,然后使用intent as参数调用startActivity
方法,例如:
Intent intent = new Intent(this, YourActivity.class);
startActivity(intent);
有关更多选项和示例,请参阅doc页面。