首先介紹功能,我要實現動態載入布局的效果,之前是採用的new組件的辦法來實現,但是android記憶體有限,new的對象會達到500多個,為了減少new的對象,我決定使用xml布局代替new的對象。
自訂控制項的布局:
自訂控制項 java類:
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) {//參數設定不合理,顯示效果很差params.width=300;params.height=100;super.setLayoutParams(params);}}
Activity布局:
MainActivity:
開啟一條線程定時發送訊息,來類比載入組件的效果,自訂群組件使用ScrollView展示,注意,這裡ScrollView內部必須要有 一個子布局。把自訂控制項new出來添加到子布局中。就可以實現每隔5秒中產生一個控制項並設定相對應的參數。
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();}}