博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android之控件与布局,结构知识点,基础完结
阅读量:5981 次
发布时间:2019-06-20

本文共 12302 字,大约阅读时间需要 41 分钟。

版权声明:未经博主允许不得转载

在Android中我们常常用到很多UI控件,如TextViewEditTextImageViewButtonImageButtonToggleButtonCheckBoxRadioButton等等这些可以自己多用就会了。

也会学到一些布局如:LinearLayout 线性布局RelativeLayout 相对布局FrameLayout 帧布局AbsoluteLayout绝对布局TableLayout 表格布局GridLayout 网格布局ConstraintLayout 约束布局

LinearLayout 线性布局:

android:orientation="vertical"android:orientation="horizontal"复制代码

RelativeLayout 相对布局

android:layout_alignParentTopandroid:layout_alignParentBottomandroid:layout_alignParentLeftandroid:layout_alignParentRight复制代码
android:layout_marginTopandroid:layout_marginBottomandroid:layout_marginLeftandroid:layout_marginRightandroid:layout_margin复制代码
android:layout_centerVerticalandroid:layout_centerHorizontalandroid:layout_centerInParent复制代码
android:layout_aboveandroid:layout_belowandroid:layout_alignLeftandroid:layout_alignRightandroid:layout_toLeftOfandroid:layout_toRightOfandroid:layout_alignBottomandroid:layout_alignTopandroid:layout_alignBaseline复制代码

TableLayout 表格布局

android:layout_spanandroid:layout_columnandroid:collapseColumnsandroid:shrinkColumnsandroid:stretchColumns复制代码

属性

android:idandroid:layout_widthandroid:match_parentandroid:textandroid:backgroundandroid:textSizeandroid:textColorandroid:inputTypeandroid:hint复制代码

结构:

AndroidManifest.xml为整个应用的主配置,清单文件,应用的包名、版本号、组件、权限等信息。

Activity的活动状态:

activity is running:为活动状态onResume()->running->onPause():为暂停状态onStart()->onResume()->running->onPause()->onStop():为停止状态onDestroy():为非活动状态复制代码
onCreate()onStart()onResume()onPause()onStop()onDestroy()onRestart()复制代码

跳转:第二个界面:

private Button mButton;private String text="dashu";mButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){  Intent data = new Intent();  data.putExtra("text",text);  setResult(2,data);  finish(); }}复制代码

跳转:第一个界面:

@Overrideprotected void onActivityResult(int requestCode,int resuleCode,Intent data){ super.onActivityResult(requestCode,resultCode,data):   if(requestCode==1&&resultCode==2){      String text = data.getStringExtra("text");      textView.setTextView(text);    }}复制代码

ListView与ArrayAdapter的搭配:

//准备数据源->适配器加载数据源->控件加载适配器public class MainActivity extends AppCompatActivity{ private ListView listView; private ArrayAdapter
list_adpater; @Override protected void onCreate(Bundle savedInsstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); listView=findViewById(R.id.listView); //1 String data[] = {
"dashu1","dashu2","dashu3"}; //2 list_adpater = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,data); //3 listView.setAdapter(list_adapter); }}复制代码

ListView与SimpleAdapter的搭配:

//列表项//布局
//单个列表项
复制代码
private ListView listView;private List
> dataList;private SimpleAdapter simple_adapter;//1.dataList = new ArrayList<>();dataList=getData();private List
> getData(){ for(int i = 0;i<10;i++){ Map
map = new HashMap<>(); map.put("image",R.drawable.images1); map.put("text",i); dataList.add(map); } return dataList;}//2.simple_adapter = new SimpleAdapter(this,dataList,R.layout.item,new String[]{
"image","text"},new int[]{
"R.id.imageView","R.id.imageView"});//3.listView.setAdapter(simple_adapter);复制代码

To:

public class App{ private String appName; private int appId;  App(String appName,int appId){ }}//public class AppAdapter extentds ArrayAdapter
{ ... App app = getItem(position); View view = LayoutInflater.from(getContext()).inflate(...);}// //获取视图 @Override public View getView(int position, View convertView, ViewGroup parent) { //创建ViewHolder ViewHolder viewHolder = null; //如果为空 if (convertView == null){ //mInflater.inflate(渲染布局,parent , false) convertView = mInflater.inflate(R.layout.item_msg,parent,false); viewHolder = new ViewHolder();//创建类对象 //视图 viewHolder.mIvImg = convertView.findViewById(R.id.id_iv_img); viewHolder.mTvTitle = convertView.findViewById(R.id.id_tv_title); viewHolder.mTvContent = convertView.findViewById(R.id.id_tv_content); convertView.setTag(viewHolder);// convertView.getTag(); }else { viewHolder = (ViewHolder) convertView.getTag();// convertView.getTag(); } //获取数据位置 Message msg = mDatas.get(position);//数据集合 private List
mDatas; viewHolder.mIvImg.setImageResource(msg.getImgResId());//获取图片位置 viewHolder.mTvTitle.setText(msg.getTitle());//获取标题 viewHolder.mTvContent.setText(msg.getContent());//获取内容 return convertView; } public static class ViewHolder{ //静态内部类,类调用 ImageView mIvImg; TextView mTvTitle; TextView mTvContent; }//orApp app = getItem(position);if(convertView==null){ view=LayoutInflater.from(getContext()).inflate(resourceId, null); viewHolder=new ViewHolder(); viewHolder.imageView= view.findViewById(R.id.app_image); viewHolder.textView= view.findViewById(R.id.appl_name); view.setTag(viewHolder); }else{ view=convertView; viewHolder = (ViewHolder) view.getTag(); ... return view;}复制代码

To:

private List
> dataList;private SimpleAdapter simpleAdapter;private void getData(){ for(int i=0;i<##;i++){
Map
map = new HashMap<>(); map.put("",##); dataList.add(##); }}复制代码

ProgressBarmax,progress,secondaryProgress

style="?android:attr/progressBarStyleHorizontal"style="?android:attr/progressBarStyleLarge"style="?android:attr/progressBarStyle"style="?android:attr/progressBarStyleSamll"复制代码
int first=progressBar.getProgress();int second=progressBar.getSecondaryProgress();int max = progress.getMax();复制代码
progressBar.incrementProgressBy(5);progressBar.incrementSecondaryProgressBy(5);progress.incrementProgressBy(-5);progressBar.incrementSecondaryProgressBy(-5);复制代码
ProgressDialog progressDialog = new ProgressDialog(this);//progressDialog.setProgresssStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setTitle("");progressDialog.setIcon("");//progressDialog.setMax(100);progressDialog.incrementProgressBy(20);//progessDialog.setButton(DialogInterface.BUTTON_POSITIVE,"确定",new DialogInterface.OnClickListener(){  ...});progressDialog.setCancelable(true);//progressDialog.show();复制代码

SeekBarOnSeekBarChangeListener

... android:max="100" android:progress="40"
复制代码
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){});复制代码

日历选择器:OnDateChangedListener

//DataPicker日历选择器private DataPicker dataPicker;private Calendar calendar;private int year,day,hour,minute;//calendar = Calendar.getInstance();//year = calendar.get(Calendar.YEAR);...minute = calendar.get(Calendar.MINUTE);//DataPickerDialog-OnDateSetListener()new DatePickerDialog(this, newDatePickerDialog.OnDateSetListener(){  ...},year,calendar.get(Calendar.MONTH),day).show();//TimePicker-setOnTimeChangedListener()//TimePickerDialog-OnTimeSetListenernew TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener(){  ....},hour,minute,true).show();复制代码

Meau

//OptionsMenu,SubMenu,ContextMenu//
//
//雷同SubMenu//getMenuInflater().inflate();onCreateOptionsMenu();onCreateContextMenu();//动态onCreateOptionsMenu(Menu menu){ menu.add(1,1,1,"1"); menu.add(1,2,1,"2"); return super.onCreateOptionsMenu(menu);}onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo){ //menu.setHeaderTitle(); //menu.setHeaderIcon(); menu.add(1,1,1,"1"); menu.add(1,2,1,"2"); ... super.onCreateContextMenu(menu,v,menuInfo);}//onCreateOptionsMenu(Menu menu){ //SubMenu play=menu.addSubMenu(); play.setHeaderTitle(); play.setHeaderIcon(); play.add(); play.add(); SubMenu play2=menu.addSubMenu(); paly2.add(2,1,1,""); play2.add(2,2,1,""); return super.onCreateOptionsMenu(menu);}//ContextMenuListView = findViewById(R.id.listView);adapter = new ArrayAdapter
(this,android.R.layout.simple_list_item_1,data);listView.setAdapter(adapter);registerForContextMenu(listView);//OnOptionsItemSelectedOnOptionsItemSelected(MenuItem item){ if(item.getGroupId() == 1){ switch(item.getItemId()){ case 1: break; case 2: break; } } ...}复制代码

Notification 通知

图标(SmallIcon)标题(ContextTitle)内容(ContextText)时间(When)复制代码
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);//builder.setSmallIcon();...builder.setDefaults(Notification.DEFAULT_ALL);//PendingIntent类-setContentIntent()NotificationManager去完成发送和取消通知的事情复制代码

Dialog 对话框

//setPositiveButton()和setNegativeButton():添加确定和取消按钮AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle();...builder.setPositiveButton("确认", new DialogInterface.OnClickListener(){ ...}builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){ ...}Dialog dialog = builder.create();dialog.show();//setSingleChoiceItems()AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle();builder.setIcon();builder.setSingleChoiceItems(data,0,new DialogInterface.OnClickListener(){  ...});Dialog dialog = builder.create();dialog.show();复制代码

WebView

//uri , setAction , setDataUri uri = Uri.parse(url);Intent intent = new Intent();intent.setAction(Intent.ACTION_VIEW);intent.setData(uri);startActivity(intent);复制代码
复制代码
//webView = findViewById(R.id.webView);webView.loadUrl(url);//WebSettings webSettings = webView.getSettings();webSettings.setJavaScriptEnabled(true);//webView.setWebViewClient(new WebViewClient(){  ...});//webView.setWebChromeClient(new WebChromeClient(){   ...   //   if(dialog != null && dialog.isShowing()){     dialog.dismiss():     dialog = null;   }   ...   //    if(dialog == null){      dialog = new ProgressDialog(MainActivity.this);      dialog.setTitle();       ...      dialog.show();     }else{       dialog.setProgress(newProgress);     }}复制代码

Fragment:为了解决Android碎片化

Fragment is addedonAttach()onCreate()onCreateView()onActivityCreated()onStart()onResume()Fragement is activiteonPause()onStop()onDestroyView();onDestroy()onDetach()Fragment is destroyed复制代码
onCreate()onCreateView()onActivityCreated()onStart()onResume()复制代码
onPause()onStop()onStart()onResume()复制代码
onPause()onStop()onDestroyView()onDestroy()onDetach()复制代码
//MyFragment fragment = new MyFragment();FragementManager fragmentManager = getFragmentManager();FragmentTransaction beginTransaction = fragmentManager.beginTransaction();beginTransaction.add(R.id.layout,fragment);beginTransaction.commit();//getFragmentManager().beginTransaction().add(R.id.layout,fragment).commit();//myFragment = (MyFragment)getFragmentManager(). findFragmentById(R.id.fragment);//Fragment.javaToast.makeText(getActivity(),"dashu",Toast.LENGTH_SHORT).show();复制代码

File,SharedPreferences,SQLite

private SQLiteDatabase db;public class MyHelper extends SQLiteOpenHelper{ public static String CREATE_TABLE="create table student("   + " _id integer primary key autoincrement,"   + "name varchar(20),"   + "age integer,"   + "sex varchar(2)";   public Context mContext;     public MyHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,int version){  super(context,name,factory,version);  mContext=context;}@Overridepublic void onCreate(SQLiteDatabase db){ db.execSQL();}//Cursor cursor=db.query("student",null,null,null,null,null,null);if(cursor!=null){  while(cursor.moveToNext()){    }}复制代码

ContentProvider Android四大组件之一,为存储和获取数据提供统一的接口。 自定义类继承ContentProvider,通过android:authorities属性授权。ContentResolver内容处理者,提供ContentProvider中同名同参的增删改查方法。

boolean onCreate()String getType(Uri uri)Cursor query()Uri insert()int update()int delete()//URI : 完整的uri路径//ContentProvider内容提供者ContentResolver内容解析者复制代码

Spinner下拉框

//android:entries="@array/list"
1
2
复制代码
public class MainActivity extends AppCompatActivity{ private Spinner mSpinner;  ...   //   final String[] arrays = getResources().getStringArray(R.array.list);  //  ArrayAdapter
mSpinnerAdaper=new ArrayAdapter
(MainActivity.this,android.R.layout.simple_spinner_item,arrays); mSpinner.setAdapter(mSpinnerAdaper); //setOnItemSelectedListener() ...}复制代码

如果觉得不错,那就点个赞吧!❤️ 编辑 :达叔 定位:分享 Android&Java 知识点 我的目标是——每天不断更

你可能感兴趣的文章
《JavaScript高级程序设计》读书笔记(十):本地对象Date
查看>>
linux中fork()函数详解
查看>>
从1G到5G,46年屏幕变迁下,富士康、苹果、三星、华为的浴火重生路 ...
查看>>
##II 第四单元##管理系统中的简单分区和文件系统
查看>>
用flash测试你的ircd
查看>>
白话红黑树系列之二——红黑树的构建
查看>>
客户的一张表中出现重复数据,而该列由唯一键约束,重复值如何产生的呢?...
查看>>
MySQL5.6中新增特性、不推荐使用的功能以及废弃的功能
查看>>
OnePlus安装Kali-NetHunter
查看>>
[Oracle][DataGuard]Standby数据库文件有损坏时的处理方法
查看>>
JavaScript:Array 对象
查看>>
PDFCreator:一款免费,开源的PDF(Tiff,pcx,png,jpeg,bmp,PS,EPS)打印机(VB,GPL),并提供了COM接口,方便使用各种编程语言调用...
查看>>
Note 1773479 - SYB: Displaying multiple triggers per object
查看>>
联手云计算核心技术开发,BoCloud与中科院软件所战略合作
查看>>
2017年背景下的SSD选购技巧有哪些变化?
查看>>
2016年的数据存储和管理的成本将何去何从?
查看>>
Airpods 并非无用,而是苹果借助语音交互布局物联网的新“棋子”
查看>>
项目总结:数据迁移测试
查看>>
SQL中存储过程的创建和使用
查看>>
荷兰政府:保证不强制在任何产品中留有后门
查看>>