【问题标题】:Dynamically display a layout based on a value from a spinner根据来自微调器的值动态显示布局
【发布时间】:2018-08-28 11:02:09
【问题描述】:

使用 Android Studio 1.1.0。这就是我想要完成的事情......

我设置了一个屏幕来收集游戏的玩家人数。根据该微调器的值,我想在我的下一个活动中显示 X 数量的文本框以捕获玩家姓名。

我该如何设置?

【问题讨论】:

  • 那是你不确定如何动态生成文本框的部分吗?
  • 发布你已经放在一起的代码。我假设你的问题是什么。您有一个包含玩家数量的微调器。选择数字时,您想开始另一个活动,其中包含 x 数量的文本字段,用于在微调器中选择的数字?
  • 我投票结束这个问题,因为它没有建设性。

标签: android textbox spinner


【解决方案1】:

您可以通过在 Intent 中将它们设置为 Extra 来在 Activity 之间传递数据。这个问题解释了如何:How do I create an android Intent that carries data?

如果您有一个列表来存储玩家名称的字符串,您可以这样做,例如:

    Intent intent = new Intent();
    intent.putStringArrayListExtra("playerNames", yourList);

在您的下一个活动中,您可以创建一个 ListView(或 GridView 或您认为适合此任务的任何内容),在其中显示所有玩家名称。

【讨论】:

    【解决方案2】:

    首先从您的第一个 Activity 传递此信息:

     int numberOfPlayers;
    

    从您的微调器中获取玩家数量,但您目前将其设置为 numberOfPlayers

    然后当你开始你的新活动时传递这个

     Intent getPlayerNamesIntent = new Intent(MainActivity.this, PLayerNamesActivity.class);
     getPlayerNamesIntent.putExtra("NUM_PLAYERS", numberOfPlayers); 
     startActivity(getPlayerNamesIntent);
    

    然后在下一个 Activity onCreate 中获取您的 Extras

     @Override
     public void onCreate(Bundle savedInstanceState){
          super.onCreate(savedInstanceState);
          // Layout should create have something like LinearLAyout with orientation vertical with name android:id="@+id/linearLayoutParent"
          setContentView(R.layout.base_layout);
    
    
          LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayoutParent);
    
         // get the NUmber from extras
         int numberOfPlayers = getIntent().getExtras().getInt("NUM_PLAYERS");
    
        if(numberOfPlayers > 0){
            for(int i = 0; i < numberOfPlayers; i++){
               EditText editText = new EditText(this);
               LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
              editText.setLayoutParams(params);
              // Set Tag here, so you can use tag to get the right player later
              editText.setTag("PlayerNumber_" + Integer.toString(i)); 
              layout.addView(editText);
    
            }
        }
     }
    

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      相关资源
      最近更新 更多