代码有ListView
,点击列表项会弹出AlertDialog
。 AlertDialog
有两个单选按钮"是"和"不"然后一个" ok"按钮。
当用户选择"是"下一个Activity
开始,如果选中" no"他们留在同一个Activity
。
我的问题是:无论我选择哪个列表项,我都会接受相同的' Next-activity' 。我希望根据我选择的列表项目进行不同的活动。
listview = (ListView) findViewById(R.id.mylistview);
final String[] items = new String[]{"IOS", "ANDROID", "WINDOWS"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, items);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemposition = position;
String itemvalue = (String) listview.getItemAtPosition(position);
final CharSequence[] items1 = {"yes", "no"};
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("slection confirmation");
builder.setCancelable(false);
builder.setSingleChoiceItems(items1, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selection = (String) items1[which];
Toast.makeText(getApplicationContext(), items1[which], Toast.LENGTH_SHORT).show();
}
});
builder.setNeutralButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (selection)
{
case("yes"):
Intent myint=new Intent(MainActivity.this,secondpage.class);
myint.putExtra("act1","");
startActivity(myint);
break;
case("no"):
dialog.cancel();
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
答案 0 :(得分:0)
首先,为不同活动的所有类名创建字符串资源。在你的&res; strings.xml&#39;文件,你可以写
<string name="sFirstClass">my.package.name.MyFirstClass</string>
<string name="sSecondClass">my.package.name.MySecondClass</string>
请注意,使用完整的活动路径非常重要。
然后,在&#39; onItemClick()&#39; OnItemClickListener
的方法,定义一个String变量并根据单击列表项的位置对其进行初始化。
// 'final' is important so the String will be visible
// inside the dialog button's 'onClick()' method
final String SECONDPAGE_CLASS = getMyClass(position);
其中&#39; getMyClass()&#39;是一种匹配位置和目标活动的方法:
private String getMyClass(int pos)
{
String myClass;
switch (pos)
{
case 0: myClass = getString(R.string.sFirstClass);
break;
case 1: myClass = getString(R.string.sSecondClass);
break;
//...
default: // do whatever is appropriate
}
return myClass;
}
现在您的确定按钮可以将Intent
定义为
try
{
Intent myint = new Intent(MainActivity.this, Class.forName(SECONDPAGE_CLASS));
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
答案 1 :(得分:-1)
您在Intent中使用second.class
进行硬编码,而是尝试使用动态变量,该变量根据您点击的项目保存类的值
public static Activity ClASS_NAME;
//set CLASS_NAME based on item position for example
switch (selection)
{
case("yes"):
Intent myint=new Intent(MainActivity.this,CLASS_NAME);
myint.putExtra("act1","");
startActivity(myint);
break;
case("no"):
dialog.cancel();
break;
}