标签:
1.概念:
View组件可以用静态创建,即使XML文件,也可以用代码创建。
动态一般用代码加载;静态一般用XML加载
2.使用方法:
【1】.使用XML创建View -- 推荐使用!!
Android图形用户界面上的组件可以使用XML文件创建
XML文件中使用属性指定组件的属性,如id等。
XML文件放置在res/layout下
【2】.使用代码创建View --有时候也使会用到
每一个视图组件都是一个View类型的对象
可以在代码中,使用视图类的构造方法,创建View对象
可以调用View对象的setXXX方法,设置其属性
3.动态使用的例子:
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <Button android:id="@+id/showDateDialog" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="显示日期对话框" /> <Button android:id="@+id/showTimeDialog" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="显示时间对话框" /> </LinearLayout>
代码:
public class MainActivity extends Activity { private Button showDateDialog; private Button showTimeDialog; private int year; private int monthOfYear; private int dayOfMonth; private int hourOfDay; private int minute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showDateDialog = (Button) findViewById(R.id.showDateDialog); showTimeDialog = (Button) findViewById(R.id.showTimeDialog); // 获取系统时间 Calendar calendar = Calendar.getInstance(); year = calendar.get(Calendar.YEAR); monthOfYear = calendar.get(Calendar.MONTH); dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); Log.d("h_bl", year + "-" + monthOfYear + "-" + dayOfMonth); hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); minute = calendar.get(Calendar.MINUTE); showDateDialog.setOnClickListener(new ViewOcl()); showTimeDialog.setOnClickListener(new ViewOcl()); } /** * 点击弹出对话框的事件监听 * * @author Administrator * */ private class ViewOcl implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.showDateDialog: // 日期对话框 DatePickerDialog dateDialog = new DatePickerDialog( MainActivity.this, new DateSetCls(), year, monthOfYear, dayOfMonth); dateDialog.show(); break; case R.id.showTimeDialog: // 时间对话框 TimePickerDialog timeDialog = new TimePickerDialog( MainActivity.this, new OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Toast.makeText(getApplicationContext(), "选择时间:" + hourOfDay + "-" + minute, Toast.LENGTH_LONG).show(); } }, hourOfDay, minute, true); timeDialog.show(); break; } } } private class DateSetCls implements OnDateSetListener { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Toast.makeText( getApplicationContext(), "选择日期:" + year + "-" + (monthOfYear + 1) + "-" + dayOfMonth, Toast.LENGTH_LONG).show(); } } }
标签:
原文地址:http://www.cnblogs.com/H-BolinBlog/p/5290256.html