我有一个包含几个子元素( )的main.xml
布局和其他布局。我想要做的是动态添加为可滚动列表元素。实际上确实做到了这一点,我使用如下循环:other.xml
TextView, ImageView
main.xml
other.xml
LayoutInflater layoutInflaterInstance = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
View insertPoint = findViewById(R.id.linearLayoutToKeepOtherLayouts);
for (int i = 0; i < numberOfOtherXmlLayouts; i++) {
view = layoutInflaterInstance.inflate(R.layout.otherXml, null);
TextView firstValueOfOtherXml = (TextView) view.findViewById(R.id.first);
TextView secondValueOfOtherXml = (TextView) view.findViewById(R.id.second);
ImageView thirdValueOfOtherXml = (ImageView) view.findViewById(R.id.third);
firstValueOfOtherXml = setContent();
secondValueOfOtherXml = setContent();
thirdValueOfOtherXml = setContent();
((ViewGroup) insertPoint).addView(view, i, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
}
这就是我将动态内容添加到现有 main.xml 的方式。现在我想向 firstValueOfOtherXml/secondValueOfOtherXml/thirdValueOfOtherXml 添加一些活动,并尝试在 TextView/ImageView 中设置onClick
事件,other.xml
如下所示(在上部 for 循环中):
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.otherXmlID);
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.otherXml);
Intent myIntent = new Intent(getApplicationContext(), OtherActivity.class);
startActivityForResult(myIntent, 0);
}
};
relativeLayout.setOnClickListener(clickListener);
不幸的是,它仅适用于other.xml
添加到main.xml
. 我认为问题出在添加的 ID 中other.xml
,我不会动态更改它(可能根据i
for 循环)。在任何添加动态布局元素的解决方案中,我都将不胜感激,因为它们的子元素的 ID 发生了动态变化,以使它们的识别成为可能。
希望它足够清楚。感谢帮助。