【问题标题】:how to make a button visible / invisible in an if else loop如何在 if else 循环中使按钮可见/不可见
【发布时间】:2021-09-07 09:15:42
【问题描述】:

我正在构建一个 android 应用程序(对于那些知道它的人来说,类似于 Discord)。所有频道都显示在主页上,每个频道都有属性(名称、作者、我的;我要做的就是仅在我的频道旁边显示一个详细信息按钮(因此如果我的属性等于“t”)。 问题是,如果我写 b.setVisibility (View.VISIBLE)b.setVisibility (View.GONE) 整行会消失,因此频道名称也会消失。

主要活动:

 for(int i = 0; i < canaliJSON.length(); i ++){ 
                JSONObject obj = (JSONObject) canaliJSON.get(i); 
                String title = obj.getString("ctitle");
                String property = obj.getString("mine");

                final Button buttonHv = (Button) findViewById(R.id.hv);
                View b = findViewById(R.id.hv);
                        if (property.equals("t")) {
                            Log.d(TAG,"myChannel");
                            b.setVisibility(View.VISIBLE);
                        }
                        else {
                            Log.d(TAG,"not myChannel");
                            buttonHv.setVisibility(View.GONE);
                        }

                canali.add(new Canale(title, property + " "+ buttonHv));
            }

MainActivity.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:gravity="center_vertical"
    android:orientation="horizontal"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:padding="16dp">

    <!--Nome canale nella homepage-->

    <TextView
        android:id="@+id/canale_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_weight="1"
        android:textColor="@color/black" />


    <Button
        android:id="@+id/hv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:visibility="invisible"/>
        android:text="HV" />


</LinearLayout>

【问题讨论】:

  • 顺便说一句,为什么要将相同的视图分配给按钮和视图? ` 最终按钮 buttonHv = (Button) findViewById(R.id.hv); View b = findViewById(R.id.hv);`显示/隐藏时只需使用按钮
  • View.GONE 基本上将宽度和高度设置为 0,因此您的布局可能会崩溃,您应该尝试 .setVisibility(View.INVISIBLE) 代替。请注意,您可能还想禁用视图
  • 这个解决了吗?
  • @DevWithZachary 这只是一个测试,但即使只使用按钮,整行(包括频道名称)也会继续消失
  • @Piyush 还没有..

标签: java android xml


【解决方案1】:

为什么你用 'View' 和 'Button' 声明了 2 次按钮?
只需使用“按钮”

从您的代码中删除此行:
View b = findViewById(R.id.hv);

并使用:
buttonHv.setVisibility(View.VISIBLE)

'View' 将获取所有元素,包括 'Button' 或您使用过的任何其他标签。只需使用“按钮”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2021-09-16
    相关资源
    最近更新 更多