Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Adding view dynamically in a nested layout

I have an abc.xml with the following structure.

<ScrollView
  android:layout_width="match_parent"
  android:layout_height="match_parent">
 <RelativeView
   android:layout_width="match_parent"
   android:layout_height="wrap_content">
  <LinearLayout
    android:id="@+id/linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
  </LinearLayout>
 </RelativeLayout>
</ScrollView>

I want to add textviews dynamically to linear layout. Below is my code. I don't get any errors but I am not getting the desired results.

LayoutInflater Inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = Inflater.inflate(R.layout.abc, null);

LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear);

        TextView Tag = new TextView(getActivity());
        Tag.setText("textString");
        Tag.setBackgroundResource(R.color.bg_color);
        Tag.setTextAppearance(getActivity(), R.style.SmallFont);
        layout.addView(Tag);
like image 958
Shah Avatar asked Dec 18 '13 10:12

Shah


People also ask

Is this possible to add views in a layout dynamically in Android?

This example demonstrates How to Dynamically Add Views into View. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.

What tag should you use to add a reusable view component to a layout file?

To efficiently re-use complete layouts, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Reusing layouts is particularly powerful as it allows you to create reusable complex layouts.


1 Answers

your xml should be

<ScrollView
  android:layout_width="match_parent"
  android:layout_height="match_parent">
 <LinearLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical">
  <LinearLayout
    android:id="@+id/linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
  </LinearLayout>
 </LinearLayout>
</ScrollView>

and the java code to add your text view is

LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
TextView Tag = new TextView(getActivity());
tag.setLayoutParams(params);
Tag.setText("textString");
Tag.setBackgroundResource(R.color.bg_color);
Tag.setTextAppearance(getActivity(), R.style.SmallFont);
layout.addView(Tag);
like image 50
dinesh sharma Avatar answered Sep 28 '22 04:09

dinesh sharma