一个父线性布局被夸大,并且在for循环中添加了子视图。
但所有的儿童观点都有相同的身份。我可以通过v.getId()
找到ID,然后将ID硬编码到case "id of child view"
。但是id可能会在另一部手机上发生变化
在我的情况下,所有ID都是相同的,手动设置它们可能也是不好的做法。我希望通过onClick(View v)
- 方法调用子视图,但无法正确识别
我添加了一个树形视图来说明:tree view layout
@Override
public void onCreate(Bundle savedInstanceState) {
// extending existing parent class' methods
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.mainbase, null);
for (int i = 0; i < 4; i++) {
View custom = inflater.inflate(R.layout.identifierplate, null);
switch (i) {
case 0: {
//set layout images and text for first <include>
ImageView SensorReadout = (ImageView) custom.findViewById(R.id.sensor_icon);
SensorReadout.setImageResource(R.drawable.ic_launcher);
TextView sensor_name = (TextView) custom.findViewById(R.id.sensor_name);
sensor_name.setText(R.string.sr_1);
TextView sensor_description = (TextView) custom.findViewById(R.id.sensor_description);
sensor_description.setText(R.string.sr_2);
custom.setOnClickListener(this);
parent.addView(custom);
break;
}
case 1: {
// do same as in case 0 but different text/image
custom.setOnClickListener(this);
parent.addView(custom);
break;
}
default: { // Defaults are already set in the XML
}
}
}
setContentView(parent);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case 0: {
Intent intent = new Intent(this, First.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(this, Second.class);
startActivity(intent);
break;
}
default: {
int id = v.getId();
String ids = String.valueOf(id);
Toast.makeText(this, ids, Toast.LENGTH_SHORT).show(); //error: all have same id
}
}
}
答案 0 :(得分:0)
如何使用setview的setTag和getTag方法?
然后你可以检查getTag ==第一个孩子,并根据你的逻辑代码。
在for循环中,您可以使用带有i变量的setTag设置标记。
答案 1 :(得分:0)
Mike M.指出了正确的方向 我添加到.java:
custom.setId(R.id.id_v_2);
添加到ids.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item
type="id"
name="id_v_0" />
<item
type="id"
name="id_v_1" />
</resources>
更改了onClick()
public void onClick(View v) {
switch (v.getId()) {
case R.id.id_v_0: { ...