Reputation: 325
I'm new to android development. I have a JSON File that contains a number of objects, how do I add a new TextView to my ScrollView for every object in the JSON file? Each TextView would store the data contained in the JSON Object. The only way I know at the moment to add Views to a Layout is by defining them in the activity layout XML file, But that doesn't allow for me to automatically generate them, I have to create them all by hand and define them manually.
Thanks
EDIT: The linked duplicate didn't have any answers, however an answer has been provided here.
Upvotes: 0
Views: 829
Reputation: 149
I Supposing that you have a activity_layout.xml
and SomeActivity
and both have a relation wihch setContentView(R.layout.activity_layout)
method, called in overridden method onCreate
, like this:
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_layout)
}
Now, you need finder some ViewGroup
like: LinearLayout
, ListView
(better). Using method findViewById(R.id.some_group_view)
and cast with the same class.
With instanced variables (supposing you use ListView
) map you Json object and extract the needed information in Iterator object and pass data in you ArrayAdapter
.
See Android developer guides for make application. They have a really useful documentation.
Android developer Main page
Android developer Guides
Android developer ListView
Upvotes: 1
Reputation: 166
@Lewiky, Here is .java file code for adding TextView to a ScrollView dynamically. You can replace the loop through according to your json objects length. Also posting the xml layout file code for your reference
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 code
<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>
Hope this helps, Happy Coding. :)
Upvotes: 2