【问题标题】:How do I dynamically control the layout of an app? [duplicate]如何动态控制应用程序的布局? [复制]
【发布时间】:2018-04-01 10:39:11
【问题描述】:

我的应用上有一个屏幕,用户应该可以在其中添加提醒,然后使用开关单独切换它们(见下面的屏幕截图)

我的问题是,有什么方法可以使用 Java 从应用程序屏幕添加/删除文本视图和切换?

我是应用程序开发的新手,所以如果这是微不足道的或不可能的,我很抱歉! 干杯,奥利

【问题讨论】:

  • 你用谷歌搜索了吗?
  • 是的,但我似乎找不到我要找的东西。我可以在正确的方向提示。
  • @MohammedAtif 谢谢,这是一个有用的链接

标签: java android xml dynamic


【解决方案1】:

对您来说(在我看来)最简单的情况是添加最大数量的内部布局(TextView + 切换开关)并使用Visibility.GONE/INVISIBLE 等。

如果您想动态地执行此操作,您可以使用RecyclerView,并在列表中列出这些内容,但您在处理用户输入时会遇到一些挑战,但这并不难。

【讨论】:

    【解决方案2】:

    对于每个提醒,扩展包含 TextViewSwitch 的布局并将其添加到您的父布局。例如。你的父布局被命名为layoutReminders

    for (Reminder reminder : reminderList) {
        View reminderView = LayoutInflater.from(this).inflate(
            R.layout.item_reminder, layoutReminders, false);
    
        TextView textReminder = (TextView) reminderView.findViewById(R.id.textReminder);
        Switch switchReminder = (Switch) reminderView.findViewById(R.id.switchReminder);
    
        textReminder.setText(reminder.getDescription());
        switchReminder.setChecked(reminder.isChecked());
    
        switchReminder.setOnCheckedListener(new OnCheckedListener() ...);
    
        layoutReminder.addView(reminderView);
    }
    

    在 OnCheckedListener 中,您更新 reminderList 并相应地布局。

    【讨论】:

    • 谢谢,我试试看
    【解决方案3】:

    在线性布局中添加 textView:

     LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout);
     TextView textView= new TextView(this);
     textView.setText("some text"); 
     ll.addView(textView); 
    

    要删除线性布局中的 textView:

    LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout);
    TextView tV = (TextView) findViewById(R.id.textView);
    ll.removeView(tV);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 2011-07-22
      • 1970-01-01
      • 2021-10-03
      相关资源
      最近更新 更多