gpt4 book ai didi

android - 单击了哪个 subview ?

转载 作者:行者123 更新时间:2023-11-29 21:05:30 25 4
gpt4 key购买 nike

我有一个包含 4 个 View 的 View。我使用方法 setOnClickListener 注册了事件 View.OnClickListener

是否可以知道四个 child 中的哪个被压了?

最佳答案

尝试这种方式,希望这能帮助您解决问题。

ma​​in.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"/>

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="Button2"/>

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="Button3"/>

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="Button4"/>
</LinearLayout>

MyActivity.java

public class MyActivity extends Activity implements View.OnClickListener {


private Button button1;
private Button button2;
private Button button3;
private Button button4;
@Override
protected 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);

}

@Override
public 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;
}
}
}

关于android - 单击了哪个 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24712400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com