我遇到传感器动态按钮的问题 正如你所看到的,我得到了传感器列表,并为每个传感器分配了一个按钮。 然后我无法使onClick监听器工作,因为由于某种原因它不适合从循环生成的“1”a.k.a.“i”。
我想知道是否有人可以帮我找到解决此问题的方法,因为我很新,我在网上搜索答案,但没有其他人被迫使用整数作为ID。是的,我累了btnTag.setId(“btn”+ i),但它不承认......
public class MainActivity extends Activity implements SensorEventListener, OnClickListener {
TextView myTextView;
SensorManager mySensorManager;
TextView status;
String btn = "button";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
myTextView = (TextView) findViewById(R.id.text1);
List<Sensor> myList = mySensorManager.getSensorList(Sensor.TYPE_ALL);
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
for (int i = 1; i < myList.size(); i++) {
myTextView.append("\n" + myList.get(i).getName());
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText(myList.get(i).getName());
btnTag.setId(i);
layout.addView(btnTag);
((Button) findViewById(i)).setOnClickListener(this);
}
Toast.makeText(MainActivity.this, "done", Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.1:
Toast.makeText(getApplicationContext(), "button1 is working", 3000).show();
break;
}
}
答案 0 :(得分:0)
由于您手动设置了ID,您可以这样做.-
@Override
public void onClick(View v) {
switch (v.getId()) {
case 1:
Toast.makeText(getApplicationContext(), "button1 is working", 3000).show();
break;
}
}