First, we will introduce the function. I want to achieve the dynamic loading layout effect. Previously, we used the new component method, but the android memory is limited, so there will be more than 500 new objects, to reduce new objects, I decided to use xml layout instead of new objects.
Custom Control layout:
Custom Control java class:
Public class ViewMY extends LinearLayout {public ViewMY (Context context) {super (context); LayoutInflater mInflater = (LayoutInflater) context. getSystemService (Context. LAYOUT_INFLATER_SERVICE); View v = mInflater. inflate (R. layout. activity_main, null); this. addView (v);} public ViewMY (Context context, AttributeSet attrs) {super (context, attrs);} @ Overridepublic void setLayoutParams (android. view. viewGroup. layoutParams params) {// The parameter settings are unreasonable and the display effect is poor. width = 300; params. height = 100; super. setLayoutParams (params );}}
Activity layout:
MainActivity:
Enable a thread to send messages at a scheduled time to simulate the effect of loading components. The custom components are displayed in ScrollView. Note that a sublayout must exist in ScrollView. Add the custom control to the sub-layout. You can generate a control every five seconds and set the corresponding parameters.
public class MainActivity extends Activity {private Handler handler = new Handler(){public void handleMessage(Message msg) {if(msg.what==1){ViewMY v = new ViewMY(MainActivity.this);TextView tv = (TextView) v.findViewById(R.id.textView1);tv.setText("abcdb ="+count);v.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,600));ll.addView(v);}};};private ScrollView sv;private LinearLayout ll;int count=0;boolean isRun;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main_activity);sv = (ScrollView) findViewById(R.id.scrollView1);ll = (LinearLayout) findViewById(R.id.scrollView1_layout);isRun=true;new Thread(new Runnable() {@Overridepublic void run() {while(isRun){try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}handler.sendEmptyMessage(1);count++;if(count==10){isRun=false;}}}}).start();}}