Android中的随机布局XML

时间:2012-10-08 22:29:50

标签: android xml

我想使用此代码随机化我的布局:

public class testing extends Activity 
   {
    /** Called when the activity is first created. */
      private Integer [] mLinearLayoutIds = { 
            R.layout.games0,
            R.layout.games1,
            R.layout.games2,
            R.layout.games3,
            R.layout.games4,
            R.layout.games5,
            }; 
      public void onCreate(Bundle savedInstanceState) 
         {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
           Random random = new java.util.Random();
           int rand = random.nextInt(6);
           setContentView(mLinearLayoutIds[rand]);
         }
  }

但是,每次再次显示之前显示的布局。

如何标记之前显示的布局,使其不再显示?

2 个答案:

答案 0 :(得分:2)

这将需要持久存储。请参阅“SharedPreferences”以存储您的布局选项(或者,如果您有很多,则可以选择使用SQLite)。

每次用户启动活动时,您都应该从数组中随机选择一个事件并将其存储为已使用的数据并将其从该数组中取出。

这样做会要求您在用户第一次打开应用程序时初始化数组。

(您可以只使用一个首选项,并存储包含您的选择的JSONArray中的字符串。)

答案 1 :(得分:0)

我假设“每次”你的意思是“下次活动在背景中显示”。我认为您已将代码放入错误的方法来执行此任务。尝试将其从void onCreate()移至void onResume()

public class Testing extends Activity {
    private Integer [] mLinearLayoutIds = { 
        R.layout.games0,
        R.layout.games1,
        R.layout.games2,
        R.layout.games3,
        R.layout.games4,
        R.layout.games5,
    };

    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
    }

    public void onResume() {
        Random random = new java.util.Random();
        int rand = random.nextInt(6);
        setContentView(mLinearLayoutIds[rand]);
    }
}