How to add view in a linear layout dynamically

2019-08-31 14:06发布

I have called a make layout method that takes input label and input

public void makeLayout(String label, String inputType) {

    Toast.makeText(getApplicationContext(), label + " " + inputType,
            Toast.LENGTH_SHORT).show();

    LayoutInflater vi = (LayoutInflater) getApplicationContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.activity_main, null);

    // fill in any details dynamically here
    TextView textView = (TextView) v.findViewById(R.id.textView1);
    textView.setText("your text");

    // insert into main view
    ViewGroup insertPoint = (ViewGroup) findViewById(R.id.AdvancedCatalogContainer);
    insertPoint.addView(v, 0, new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.FILL_PARENT));

}

now on the basis of input type argument, i want to add view in the layout activity main ( inside any linear layout ). I called this method multiple times but want to display all view at once that is when the whole layout is dynamically created. What approach should be there? I want to add one thing that makes layout method of main activity is called from an asynchronous task. I need your valuable suggestion as I am new to android technology.

1条回答
乱世女痞
2楼-- · 2019-08-31 14:25

First, you have to get familiar with java (in my opinion).

1) declare a linear layout at XML layout. like:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical"
       android:id="@+id/AdvancedCatalogContainer"
       >
        </LinearLayout>

2) Get a referance to that view:

private LinearLayout rootView=findViewById(R.id.AdvancedCatalogContainer);

3) Declare a method like this:

public void fillLayout(LinearLayout root,TextView  v){
  v.setText("your text")
  root.addView(v);
}

4) Call this method in your onCreate method or anywhere in ui thread.

... extends AsycTask<blah,blah,blah>{
onPostExecute(blah){

  for(many times){

    fillLayout(linearLayout,textView);

  }

}

Edit

If you want to show a collection of data like a scrolling list please consider using ListView or RecycleView instead.

查看更多
登录 后发表回答