gpt4 book ai didi

android - 如何按字符串名称打开 fragment ?

转载 作者:行者123 更新时间:2023-11-29 14:37:35 26 4
gpt4 key购买 nike

我想打开一个随机 fragment 。现在我打开它生成一个随机数并使用开关、案例 1、案例 2 等,我打开 fragment 1、2 等。这些 fragment 是级别,它们的名称是:Nivel1、Nivel2 等。

但是我想做100多个关卡,如果用这种方法代码量会很大。有什么方法可以生成随机数,然后如果数字是 2 则显示 Nivel2() fragment 等?

这是我的实际代码:

public class Xtreme extends Activity {
String SiguienteNivel;
static int randomFragmentNum;
static int NivelesTotales=30;
static Random random = new Random();
FragmentManager fragmentManager = getFragmentManager();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xtreme);
randomFragmentNum = random.nextInt(7);
Fragment();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.xtreme, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

public void Fragment() {
switch (randomFragmentNum) {
case 0: {
fragmentManager.beginTransaction().replace(R.id.container, new Nivel1()).commit();
break;
}
case 1: {
fragmentManager.beginTransaction().replace(R.id.container, new Nivel2()).commit();
break;
}
case 2: {
fragmentManager.beginTransaction().replace(R.id.container, new Nivel3()).commit();
break;
}
case 3: {
fragmentManager.beginTransaction().replace(R.id.container, new Nivel4()).commit();
break;
}
case 4: {
fragmentManager.beginTransaction().replace(R.id.container, new Nivel5()).commit();
break;
}
case 5: {
fragmentManager.beginTransaction().replace(R.id.container, new Nivel6()).commit();
break;
}
case 6: {
fragmentManager.beginTransaction().replace(R.id.container, new Nivel7()).commit();
break;
}
case 7: {
fragmentManager.beginTransaction().replace(R.id.container, new Nivel8()).commit();
break;
}
}
}
}

最佳答案

您可以通过名称创建一个类:

try{
Fragment f = (Fragment)(Class.forName("com.example.Fragment"+i).newInstance());
fragmentManager.beginTransaction().replace(R.id.container,f).commit();
}catch(ClassNotFoundException e){
Log.e("loading level","level class not found",e);
}

关于android - 如何按字符串名称打开 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27137648/

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