android studio 新增控制元件的三種方式
阿新 • • 發佈:2018-12-05
寫在這裡以作筆記。
第一種:佈局檔案中新增
佈局檔案中: <android.support.percent.PercentFrameLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/StartDate" android:hint="點選選擇開始日期" android:layout_gravity="left" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="---" android:layout_gravity="center"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/EndDate" android:hint="點選選擇結束日期" android:layout_gravity="right"/> </android.support.percent.PercentFrameLayout> 程式碼實現: StartDate = (EditText) findViewById(R.id.StartDate); EndDate = (EditText) findViewById(R.id.EndDate); StartDate.setText(year + "年" + (month + 1) + "月" + dayOfMonth + "日")
第二種:程式碼實現新增
先新增ID <item name="TextView_Inspection_Sites" type="id"/> <item name="TextView_Inspection_Param" type="id"/> 程式碼實現新增: TextView TextView_Inspection_Sites=new TextView(this); TextView_Inspection_Sites.setId(R.id.TextView_Inspection_Sites); TextView_Inspection_Sites.setText("檢修部位:" + list.get(i).getInspectionSites().getSiteName()); TextView_Inspection_Sites.setTextSize(18); ViewGroup.LayoutParams layout_TextView_Inspection_Sites=new AppBarLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); TextView_Inspection_Sites.setLayoutParams(layout_TextView_Inspection_Sites); lineLayout.addView(TextView_Inspection_Sites); TextView TextView_Inspection_Param=new TextView(this); TextView_Inspection_Param.setId(R.id.TextView_Inspection_Param); TextView_Inspection_Param.setText("巡檢內容:" + list.get(i).getInspectionParams().getPhenomenon()); TextView_Inspection_Param.setTextSize(18); LinearLayout.LayoutParams layout_TextView_Inspection_Param=new AppBarLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); TextView_Inspection_Sites.setLayoutParams(layout_TextView_Inspection_Param); lineLayout.addView(TextView_Inspection_Param);
第三種:在程式碼中實現動態新增
佈局檔案中新增如下程式碼: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginTop="10dp" android:background="@color/gray"/> </LinearLayout> 點選事件中新增如下程式碼: LinearLayout lin=(LinearLayout)getLayoutInflater().inflate(R.layout.aline, lineLayout,false); lineLayout.addView(lin); 本例中新增的是一條線