我如何根据JSON文件的内容动态添加TextView到我的布局?

我是新的android开发。 我有一个JSON文件,其中包含一些对象,如何添加一个新的TextView到我的ScrollView的每个对象在JSON文件? 每个TextView将存储包含在JSON对象中的数据。 我目前知道将视图添加到布局的唯一方法是通过在活动布局XML文件中定义它们,但是这不允许我自动生成它们,我必须手工创建它们并手动定义它们。

谢谢

编辑:链接的副本没有任何答案,但在这里提供了答案。

@Lewiky,下面是.java文件代码,用于动态地将TextView添加到ScrollView。 你可以根据你的json对象的长度来替换循环。 另外张贴的XML布局文件代码供您参考

 public class Scrollview extends AppCompatActivity { ScrollView scrollview; LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scrollview); scrollview = (ScrollView) findViewById(R.id.scrollView); linearLayout=(LinearLayout)findViewById(R.id.scrllinear); TextView textView; LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); for (int i = 0; i < 5; i++) { textView = new TextView(this); textView.setText("I=" + i); linearLayout.addView(textView, lp); } } } 

XML代码

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/relative" android:layout_width="match_parent" android:layout_height="match_parent"> <ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/scrllinear" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </ScrollView> </RelativeLayout> 

希望这有助于快乐编码。 🙂

我假设你有一个activity_layout.xmlSomeActivity ,两者都有一个关联wihch setContentView(R.layout.activity_layout)方法,在重写方法onCreate调用,如下所示:

 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_layout) } 

现在,你需要找到一些像ViewGroupLinearLayoutListView (更好)。 使用方法findViewById(R.id.some_group_view)并使用相同的类进行投射。

使用instanced变量(假设你使用ListView )映射你的Json对象,并在Iterator对象中提取需要的信息,并在你的ArrayAdapter传递数据。

请参阅Android开发人员指南以了解make应用 他们有一个非常有用的文件。

Android开发人员主页面
Android开发者指南
Android开发人员ListView