我在 Android Studio 中遇到问题,我不知道如何一般导入开关 ID,所以我可以从所有开关调用此函数。 我尝试添加开关的描述及其编号,这样我就可以获得像“1”这样的数字。
public class MainActivity extends AppCompatActivity {
Switch switch1, switch2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switch1 = findViewById(R.id.switch1);
switch2 = findViewById(R.id.switch2);
}
public void OnClick(View view) {
String stateSwitch = "";
if(switch1.isChecked() == false){
stateSwitch = "0";
} else {
stateSwitch = "1";
}
if(switch2.isChecked() == false){
stateSwitch = "0";
} else {
stateSwitch = "1";
}
String idSwitch = switch1.getContentDescription().toString();
// What can I put instead of "switch1" or "switch2" to select the switch generically?
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute("switch", stateSwitch, idSwitch);
}
}
开关的 XML
<Switch
android:id="@+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="2"
android:onClick="OnClick"
android:text="switch2" />
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="1"
android:onClick="OnClick"
android:text="switch1" />
抱歉我的英语不好。
最佳答案
要在代码中获取小部件的 ID,只需获取 view.getId()
它将返回一个用于标识 View 的正整数,
一般情况下,要获取 id,您可以调用
String mId = Integer.toString(view.getId());
当您点击switch1
时,它将返回switch1
的id
,与您点击switch2
时类似将返回 switch2
的 id
。
关于java - 从 XML Android Studio 导入 ID 开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49842515/