java - 如何通过动态设置id动态添加自定义布局?

标签 java android android-layout android-intent android-listview

我有一个 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添加一些 Activity ,我尝试在TextView/ImageView中的other.xml中设置onClick事件,如下所示(在上面的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);

不幸的是,它仅适用于添加到 main.xml 的第一个 other.xml 布局。我认为问题出在添加的 other.xml 的 ID 中,我没有动态更改它(可能根据 for 循环中的 i )。我希望能够通过动态更改其子元素的 ID 来添加动态布局元素的任何解决方案,以使它们的识别成为可能。

希望它足够清楚。 感谢您的帮助。

最佳答案

您误解了 android 项目的模式: Activity 是每件事发生的背景。每个 Activity 都有自己的 View ,可以使用 setContentView 设置 View ,因此当您使用 setContentView 时,您实际上是在设置当前 Activity 的 View 。

您要做的第一件事是启动一个 Activity(这是全局上下文),然后在该 Activity 中执行您必须执行的任何工作

所以你应该首先像你一样启动你的新 Activity :

     @Override
     public void onClick(View v) {
           Intent myIntent = new Intent(getApplicationContext(), OtherActivity.class);
           startActivityForResult(myIntent, 0);
     }

并且在 OtherActivity 类的 onCreate 方法中,您应该 setContentView 想要应用于新的当前 Activity 的任何布局 xml 文件。

Xml文件仅用于描述 View 。(实际上你可以使用Java来做到这一点)

关于java - 如何通过动态设置id动态添加自定义布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18801379/

相关文章:

java - 为什么在增强 for 循环后返回 i 时会出现编译错误?

java - 把一个整数分成k份

android - future 通知的时间戳不正确

android - 如何解析 TFL api

android - 页面上的自定义水平选择器

java - DateTimeFormatter 不能与 ofPattern 或 OFFSET 一起使用

java - 将对象添加到数组时动态增加数组长度

android - 在多状态转换中只有第一个转换有效

android - Android中选项卡的生命周期

android - 如何设置 TimePicker 显示格式为 24 小时