android 動態載入自訂控制項

來源:互聯網
上載者:User

首先介紹功能,我要實現動態載入布局的效果,之前是採用的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();}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.