gpt4 book ai didi

android - 如何获取 setOnCheckedChangeListener 以在 Android 中动态添加多个切换按钮

转载 作者:太空狗 更新时间:2023-10-29 15:11:46 26 4
gpt4 key购买 nike

我已在 activity 中成功添加动态多个 togglebutton。但是我无法处理每个 togglebuttonsetOnCheckedChangeListener

我创建了演示代码 fragment 。

linearLayout = (LinearLayout) findViewById(R.id.linearLayout);

for (int i = 0; i < 6; i++) {

el = new LinearLayout(this);
el.setOrientation(LinearLayout.HORIZONTAL);

LinearLayout.LayoutParams emailLinearParams = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

el.setLayoutParams(emailLinearParams);
el.setPadding(5, 5, 5, 5);

LinearLayout.LayoutParams emailTxtParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 0.9f);

TextView emailTxt = new TextView(this);
emailTxt.setText("demo");
emailTxt.setLayoutParams(emailTxtParams);
emailTxt.setGravity(Gravity.CENTER_VERTICAL);

el.addView(emailTxt);

ToggleButton toggleEmailBtn = new ToggleButton(this);

LinearLayout.LayoutParams emailToggleBtnParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.1f);

toggleEmailBtn.setLayoutParams(emailToggleBtnParams);

el.addView(toggleEmailBtn);

linearLayout.addView(el);

}

最佳答案

尝试并解决了很好的答案:)

ToggleButton tglBtn[];

onCreate()

tglBtn = new ToggleButton[6];

for (int i = 0; i < 6; i++) {

el = new LinearLayout(this);
el.setOrientation(LinearLayout.HORIZONTAL);

LinearLayout.LayoutParams emailLinearParams = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

el.setLayoutParams(emailLinearParams);
el.setPadding(5, 5, 5, 5);

LinearLayout.LayoutParams emailTxtParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 0.9f);

TextView emailTxt = new TextView(this);
emailTxt.setText("demo");
emailTxt.setLayoutParams(emailTxtParams);
emailTxt.setGravity(Gravity.CENTER_VERTICAL);

el.addView(emailTxt);

tglBtn[i] = new ToggleButton(this);

LinearLayout.LayoutParams emailToggleBtnParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.1f);

tglBtn[i].setLayoutParams(emailToggleBtnParams);

el.addView(tglBtn[i]);

linearLayout.addView(el);

tglBtn[i]
.setOnCheckedChangeListener(handleOnClick(
tglBtn[i], i));

}

使用方法来处理 togglebuttons 上的 onclick

CompoundButton.OnCheckedChangeListener handleOnClick(
final ToggleButton button, final int id) {
return new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton cbtn, boolean isCheck) {
Log.d(TAG, "clicked "+id);
}
};
}

关于android - 如何获取 setOnCheckedChangeListener 以在 Android 中动态添加多个切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15923455/

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