很抱歉再次询问,但我无法从传感器列表中为我的动态 onClick 按钮实现“标记”功能。
如您所见,我已根据传感器的类型选择了按钮标签,并相应地设置了标签。但是,当我尝试使用 onClick 功能时它不起作用,请向下滚动以查看它。程序没有错误,当我按下按钮时,吐司没有出现。
我是否通过 get tag 正确实施?
public class MainActivity extends Activity implements SensorEventListener, OnClickListener {
String tag;
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);
btnTag.setTag(myList.get(i).getName());
layout.addView(btnTag);
((Button) findViewById(i)).setOnClickListener(this);
// btnTag.setOnClickListener(this);
}
Toast.makeText(MainActivity.this, "done", Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
tag = (String) v.getTag();
if (tag == "Goldfish 3-axis Magnetic field sensor")
{
Toast.makeText(MainActivity.this, "Button1 is Pressed", Toast.LENGTH_SHORT).show();
}
}