【问题标题】:How to make views visible per button click如何使每次按钮单击时视图可见
【发布时间】:2016-11-06 05:40:52
【问题描述】:

我正在开发一个可以进行一些计算的应用程序。它由一个水平的linearLayout 组成,每个布局都有 2 个编辑文本和一个微调器。我想以这样一种方式使用户可以在需要添加更多详细信息时通过单击按钮添加布局。

在我的 XML 中,我设置了 android:visibility="gone",在 Java 中,我设置了 onClick 方法以将“消失”的线性布局设置为 view.VISIBLE。它起作用了,但是一旦我单击 + 按钮,它就会显示所有线性布局。我希望它们一个接一个地出现(一个出现,而其他的保持“消失”,直到我再次单击该按钮)

【问题讨论】:

  • 每隔一段时间使用句号(句点)。这个词是按钮

标签: android android-layout


【解决方案1】:

您可以使用 Layout inflater。

创建另一个资源文件,在其中添加您需要的布局和小部件 例如 item_resource.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" />

   <Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />

  <!-- other layout elements which are required -->

</LinearLayout>

然后在 onClick 事件上务实地扩大布局

  LayoutInflater inflater = (LayoutInflater)context.getSystemService
  (Context.LAYOUT_INFLATER_SERVICE);
  View view = inflater .inflate(R.layout.item_resource,null);
  Button button =(Button)view.findViewById(R.id.btn);
  button.setText("  ");   // set value

将此视图添加到您的主布局 例如

 LinearLayout myLayout=(LinearLayout)findViewById(R.id.xx);
 mylayout.add(view);

【讨论】:

  • 它只需单击一次,但如果我再次单击该按钮,它不会添加。我希望它能够在每次单击按钮时添加布​​局。谢谢。
  • 如果您想在按钮单击时添加新视图,请使用 RecycleView 和自定义适配器。通过覆盖自定义适配器的 getView () 方法,在单击按钮时向 RecyleView 添加新项目
  • 你能帮我提供一个示例代码吗?谢谢。
  • 希望对你有帮助[这个] (stackoverflow.com/questions/17525886/…)
【解决方案2】:

在这种情况下使用片段。您可以添加任何片段以通过事件查看。

【讨论】:

  • 我是 android 新手,请详细了解
  • Fragment 表示 Activity 中的行为或用户界面的一部分。您可以在单个活动中组合多个片段以构建多窗格 UI 并在多个活动中重用一个片段。您可以将片段视为活动的模块化部分,它有自己的生命周期,接收自己的输入事件,并且可以在活动运行时添加或删除(有点像“子活动”,您可以在不同的活动中重复使用)。
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
相关资源
最近更新 更多