Java 具有多个按钮的片段-所有按钮都具有相同的ID-如何隐藏所有按钮?

Java 具有多个按钮的片段-所有按钮都具有相同的ID-如何隐藏所有按钮?,java,android,android-fragments,Java,Android,Android Fragments,我有一个片段,在里面我膨胀了另一个布局文件。这意味着页面上有多个具有相同ID的按钮: <Button android:layout_height="30dp" android:layout_width="wrap_content" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="8dp" android:text="Del

我有一个片段,在里面我膨胀了另一个布局文件。这意味着页面上有多个具有相同ID的按钮:

<Button android:layout_height="30dp"
        android:layout_width="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        android:text="Delete"
        android:id="@+id/delete_seed" tools:layout_editor_absoluteX="0dp"
        android:textSize="10sp" android:paddingTop="5dp"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:paddingBottom="5dp"
        android:padding="5dp"/>

它只删除第一个。如何定位所有按钮?

您在片段中包含了一个布局。要定位该按钮,您需要找到与包含的布局相关的按钮id,而不是根视图

View includedLayout = rootView.findViewById(R.id.include_id);
Button deletebutton = rootView.findViewById(R.id.delete_seed);
deletebutton.setVisibility(View.GONE);

//Find included button
Button includedDeleteButton = includedLayout.findViewById(R.id.delete_seed);
includedDeleteButton.setVisibility(View.GONE);

您可以使用
tag
而不是
id
,并循环执行此处解释的所有内容:

解决方法:使用id不是一种好的做法。最好使用tag。但作为一种解决方法,请使用以下代码

private void hideViews(int id, ViewGroup view) {
    for (int i = 0; i < view.getChildCount(); i++) {
        View v = view.getChildAt(i);
        if (v instanceof Button && v.getId() == id) {
           v.setVisibility(View.GONE)
        } else if (v instanceof ViewGroup) {
            this.loopViews((ViewGroup) v);
        }
    }
} 
private void hideViews(int-id,ViewGroup视图){
for(int i=0;i
更改id并使用varags方法发送多个id。所有id都相同。。。如果你不让id唯一/可用,为什么要有id?@Stultuske好吧,我明白了,但我怎么能做得不同呢?好吧,但我怎么能循环浏览页面上的所有视图?你需要循环浏览包含的布局和根布局。使用rootView和includedLayout中的视图组从布局中获取所有视图的列表<代码>视图组vg=rootView.getParent()
private void hideViews(int id, ViewGroup view) {
    for (int i = 0; i < view.getChildCount(); i++) {
        View v = view.getChildAt(i);
        if (v instanceof Button && v.getId() == id) {
           v.setVisibility(View.GONE)
        } else if (v instanceof ViewGroup) {
            this.loopViews((ViewGroup) v);
        }
    }
}