java - 从 XML Android Studio 导入 ID 开关

标签 java android android-view

我在 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时,它将返回switch1id,与您点击switch2时类似将返回 switch2id

关于java - 从 XML Android Studio 导入 ID 开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49842515/

相关文章:

java - 使用 OpenGL-ES2 Android 放大 map

java - 重定向到 play framework 2.0 中的外部 url

java - 此 URL 不支持 HTTP 方法 GET

android - Android 4.4 KitKat 中的某些用户无法绘制自定义 View

android - 如何设置cordova webview 背景,或者缓存?

java - JFrame 未正确加载

iphone - phoneGap/钛开发

android - 在 onDestroy 和 onDetach 中清除 fragment

android - 具有未烘焙纹理的 3D 对象在 metaio sdk 中无法正确呈现

Android隐藏膨胀 View