Which Child-view Was Clicked?
I have a View which contains 4 views. I registered to the event View.OnClickListener by using the method setOnClickListener. Is it possible to know which of the four child was pre
Solution 1:
Try this way,hope this will help you to solve your problem.
main.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Button1"/><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:text="Button2"/><Buttonandroid:id="@+id/button3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:text="Button3"/><Buttonandroid:id="@+id/button4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:text="Button4"/></LinearLayout>MyActivity.java
publicclassMyActivityextendsActivityimplementsView.OnClickListener{
private Button button1;
private Button button2;
private Button button3;
private Button button4;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}
@Overridepublic void onClick(View v) {
switch (v.getId()){
case R.id.button1:
Toast.makeText(this,"Button 1 click",Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(this,"Button 2 click",Toast.LENGTH_SHORT).show();
break;
case R.id.button3:
Toast.makeText(this,"Button 3 click",Toast.LENGTH_SHORT).show();
break;
case R.id.button4:
Toast.makeText(this,"Button 4 click",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
Solution 2:
You need to set tag to your views and set them to be clickable.
Later on you can get the id by view.gettag() inside this method
publicvoidonClick(View v){
int id = v.getTag();
switch(id){
case0:
break;
default:
break;
}
}
Solution 3:
You can try this:
parent.setOnClickListener(newOnClickListener(){
@OverridepublicvoidonClick(View v) {
ViewGroupparent= (ViewGroup)v;
for(intindex=0; index < parent.getChildCount(); index++){
Viewchild= parent.getChildAt(index);
}
}
});
Solution 4:
for every child
android:duplicateParentState="true"
Post a Comment for "Which Child-view Was Clicked?"