How to add view in a linear layout dynamically

房东的猫 提交于 2019-12-11 20:39:57

问题


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:


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.



来源:https://stackoverflow.com/questions/31047502/how-to-add-view-in-a-linear-layout-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!