2016-09-30 74 views
1
ArrayList<View> allButtons; 
String button; 
button = ((RelativeLayout) findViewById(R.id.activity_main)).getTouchables().toString(); 

System.out.println(button); 

输出:获取按钮ID不整个按钮

System.out的:[android.support.v7.widget.AppCompatImageButton {7107785 VFED..C .. ........ 32,74-176,210#7f0b0056 app:id/imageButton2},android.support.v7.widget.AppCompatButton {c4b99da VFED..C .. ... P .... 66,256-242,352#7f0b0057 app:id/button} ]

我怎样才能得到公正的ID是button

+0

使用'button.getId();' –

回答

4

ArrayList<View> allTouchables = ((RelativeLayout) findViewById(R.id.activity_main)).getTouchables(); 
for (View view : allTouchables) { 
    System.out.println(view.getId()); 
} 

正如上面的代码返回目前为特定的容器中的所有可触摸的观点你应该写你的代码,你也应该检查一下看法一样

ArrayList<View> allTouchables = ((RelativeLayout) findViewById(R.id.activity_main)).getTouchables(); 
for (View touchable : allTouchables) { 
    // To check if touchable view is button or not 
    if(touchable instanceof Button) { 
     System.out.println(touchable.getId()); 
    } 
} 

类型

要获得id的字符串表示形式,您可以编写

String idString = view.getResources().getResourceEntryName(view.getId()); 
+0

'System.out:2131427414 System.out:2131427415'这是我得到的我可以用它来再次查找所述元素?我的意思是我想用这个ID再次找到说元素 –

+0

@BrownmanRevival更新的答案请检查。 –

+0

我希望第一个获得所有可触摸物,不需要关于仅字符串表示形式的类型。将它和回来 –

2

aah你可以在添加到数组列表之前检查视图的类型。

ArrayList<Button>buttons = new ArrayList<>(); 
parentLayout = (RelativeLayout)findViewById(parentID); 

for(int i=0; i<parentLayout.getChildCount(); i++){ 
    View view = parentLayout.getChildAt(i); 

    if(view instanceof Button){ 
     buttons.add((Button)view); 
    } 
} 
0

所以你想检查哪个按钮被点击的布局和相应的过程。

这可以通过两种方式来实现。

1.随着的getId()

XML

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Next Layout" 
    android:id="@+id/Next" 
    android:layout_centerVertical="true" 
    android:layout_centerHorizontal="true" /> 

YourActivity

final Button nxtbtn = (Button) findViewById(R.id.Next); 



    nxtbtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      int ID = nxtbtn.getId(); 

      if(ID == R.id.Next) // your R file will have all your id's in the literal form. 
      { 
       Log.e(TAG,""+ID); 
      } 
     } 
    }); 

2. TAG

XML

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Next Layout" 
    android:tag="buttonA" 
    android:id="@+id/Next" 
    android:layout_centerVertical="true" 
    android:layout_centerHorizontal="true" /> 

在XML只需添加一个标记属性

你的活动

final Button nxtbtn = (Button) findViewById(R.id.Next); 



    nxtbtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      String Tag = nxtbtn.getTag().toString(); 
      Log.e("TAG", "" + Tag); 
      if (Tag.equal("ButtonA")){ /* Your code here */} 
     } 
    }); 

希望这可以帮助。