Android Studio學(xué)習(xí)
1.活動的基本用法
1.新建一個活動摘昌,會有主函數(shù)和其相對布局。
上面的圖片就是在setContenView()中添加我們自主創(chuàng)建的一個活動ID;
2.在AndroidMainfirst文件中注冊活動
? ? * **所有的活動都需要在AndroidMainfirst文件中進(jìn)行注冊才能生效**悼嫉,配置活動的方法:在的標(biāo)簽內(nèi)部加入標(biāo)簽,并且在標(biāo)簽里面添加
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
這串代碼相當(dāng)于把fFirstActivity設(shè)置為主活動(即點擊桌面應(yīng)用程序圖標(biāo)時,打開的就是這個活動)论皆,打開一個空活動時,標(biāo)題欄下面的就是在layout中編寫的界面。
3.在活動中使用Toast
? ? * 首先需要定義一個彈出Toast的觸發(fā)點点晴,首先在layout中創(chuàng)建一個button按鈕感凤,把這個按鈕當(dāng)做Toast的觸發(fā)點,實現(xiàn)效果是:當(dāng)你點擊button時粒督,頁面會彈出一個提醒方式陪竿。
? ? * 在onCreate()方法中添加如下代碼:
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Buttonbutton1=(Button)findViewById(R.id.button_1);
button1.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(Viewv) {
Toast.makeText(FirstActivity.this,"you clicked button 1",
Toast.LENGTH_SHORT).show();
? ? ? ? ?? }
? ? ?? });
* 在活動中可以通過findViewByID()的方法來獲取到布局文件中定義的元素,首先需向下轉(zhuǎn)型把button變成Button的實例化對象屠橄。setOnClickListener()為按鈕注冊了一個監(jiān)聽器族跛,點擊按鈕就睡執(zhí)行onClick中的功能。所以锐墙,彈出提示Toast的功能代碼就在onClick函數(shù)中書寫了礁哄。makeText方法中有三個參數(shù),第一個是Context的對象溪北,直接導(dǎo)入主活動就行桐绒;第二個參數(shù)是Toast中的顯示的內(nèi)容;第三個參數(shù)是顯示時長之拨,有兩個內(nèi)置常量可以選擇茉继,Toast.LENGTH_SHORE ?? Toast.LENGTH_LONG
4.在活動中使用菜單MENU
1.首先要在res目錄下面新建一個menu文件夾,然后在這個文件夾下面創(chuàng)建一個名為main的菜單文件敦锌。然后再main.xml中添加代碼:
<menuxmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/add_item"
android:title="Add"/>
<item
android:id="@+id/remove_item"
android:title="Remove"
/>
</menu>
這里創(chuàng)建了兩個菜單項馒疹,title就是給具體的菜單項一個標(biāo)識符。創(chuàng)建完成后需要在返回FirstActivity中重寫onCreateOptionsMenu()和onOptionsItemSelected()方法
@Override
publicbooleanonCreateOptionsMenu(Menumenu) {
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
@Override
publicbooleanonOptionsItemSelected(@NonNullMenuItemitem) {
switch(item.getItemId()) {
caseR.id.add_item:
Toast.makeText(this,"雪寶兒最美",
Toast.LENGTH_SHORT).show();
break;
caseR.id.remove_item:
Toast.makeText(this,"凱哥哥最帥",
Toast.LENGTH_SHORT).show();
break;
default:
?? }
returntrue;
}
onOptionsItemSelected()方法中定義的是菜單響應(yīng)事件乙墙,item.getItemId()是用來判斷點擊的是哪一個具體的菜單事項颖变,然后在每個菜單事項下面添加自己的邏輯代碼。
多種菜單的創(chuàng)建:
<?xmlversion="1.0"encoding="utf-8"?>
<menuxmlns:android="http://schemas.android.com/apk/res/android">
<item
android:title="listview效果顯示"
android:id="@+id/list_view">
<menu>
<item
android:title="垂直標(biāo)準(zhǔn)"
android:id="@+id/listview_vertical_stander">
</item>
<item
android:title="垂直反向"
android:id="@+id/listview_vertical_reverse">
</item>
</menu>
</item>
<item
android:title="grad_view效果顯示"
android:id="@+id/grad_view"
>
<menu>
<item
android:title="垂直標(biāo)準(zhǔn)"
android:id="@+id/gradview_vertical_stander">
</item>
<item
android:title="垂直反向"
android:id="@+id/gradview_vertical_reverse">
</item>
</menu>
</item>
<item
android:title="瀑布流效果顯示"
android:id="@+id/stagger_view"
>
<menu>
<item
android:title="垂直標(biāo)準(zhǔn)"
android:id="@+id/stagview_vertical_stander">
</item>
<item
android:title="垂直反向"
android:id="@+id/stagview_vertical_reverse">
</item>
</menu>
</item>
</menu>
onCreateOptionsMenu()和onOptionsItemSelected()方法與普通菜單方法無異听想,第一個是加載菜單(將菜單布局添加至主布局中)腥刹,第二個方法用來添加菜單的事件,里面可以添加一些邏輯事件汉买。
5.使用intent在各個活動中穿梭
首先需要創(chuàng)建一個新的活動衔峰,但是不要將其設(shè)置為主活動。個人比較喜歡用顯示intent蛙粘,所以直接記錄顯示intent的用法垫卤。
首先先創(chuàng)建一個intent,傳入FirstActivity作為上下文出牧,傳入ThirdActivity作為目標(biāo)活動穴肘,然后通過startActivity(intent2)就可以執(zhí)行這個intent了。
button1.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(Viewv) {
Intentintent=newIntent(FirstActivity.this,ThirdActivity.class);
startActivity(intent2)舔痕;
?? }
});
6.LinearLayout 布局文件模板:
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
7.修改APP名字和圖標(biāo)
android:icon="@mipmap/app_fengmian"http://在這個里面修改圖標(biāo)
android:label="@string/app_name"http://在這個里面修改名字
2.Ui開發(fā)控件知識
1.TextView
textview就是很簡單的文本顯示评抚,在layout中編輯
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello world"
layout_width和layout_height制定了控件的寬度和高度豹缀,安卓中所有的控件都有這些屬性。match_parent指讓當(dāng)前控件的大小和父布局一樣慨代,也就是由父布局來決定當(dāng)前控件的大小邢笙,wrap_content表示讓當(dāng)前控件的大小能剛好包含其中的內(nèi)容android:gravity="center"表示文字的對齊方式,指定center就是文字在水平和垂直方向上都是居中對齊的侍匙。至于字體的大小和顏色氮惯,自己考慮。
2.EditText
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginTop="0dp"/>
可以輸入內(nèi)容丈积,文本輸入框筐骇。
hint屬性就是一個比較高端的屬性,它可以在文本輸入框內(nèi)顯示提示(在輸入內(nèi)容之前)江滨,在輸入內(nèi)容時,這個提示就會消失厌均。
特殊屬性:singleLine 是單行輸入唬滑、inputtype是輸入類型,設(shè)置為textPassWord就是密碼類型棺弊,輸入的時候顯示安全鍵盤
賬號密碼匹配代碼:
3.ImageView
<ImageView
android:id="@+id/imageView2"
android:layout_width="149dp"
android:layout_height="222dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="89dp"
android:layout_marginRight="100dp"
app:srcCompat="@drawable/jingerjie"/>
src屬性就是從drawle中調(diào)用圖片的晶密,給ImageView指定了一張圖片
4.button
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button_1"
android:text="報君黃金臺上意,提攜玉龍為君死"
android:background="@android:color/transparent"
android:textSize="25sp"
android:textColor="#000000"
/>
尤其注意模她, android:background="@android:color/transparent"這串代碼可以讓按鈕的背景顏色改成透明稻艰,以后再軟件美化中可以用到
button按鈕的實現(xiàn):
Buttonbutton=findViewByid(R.id.button_1);
button.setOnClickListener(newView.OnClickListemer(){
publicvoidonClick(Viewview) {
});
intent 跳轉(zhuǎn)的實現(xiàn);
Intentintent3=newIntent(FirstActivity.this,ForthActivity.class);
startActivity(intent3);
1.拖動條(progressBar)
1.自己理解就是一個簡單的控件而已,至于進(jìn)度條想什么時候走完沒所謂侈净,反正是做假的尊勿。在.xml文件中直接定義就行
<ProgressBar
android:id="@+id/pb"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="60"/>
android:max : 進(jìn)度條的最大值
android:progress : 進(jìn)度條的精度,自己定義的(所以我說都是假的)
android:indeterminate : 如果設(shè)置為true畜侦,就是不顯示進(jìn)度條的精度
style : 就是設(shè)置進(jìn)度條的樣式元扔,是什么類型的,大或小旋膳,圓形或者水平(安卓自帶樣式)
2.實現(xiàn)一個進(jìn)度條的進(jìn)度(自動和手動兩種方式)
自動:
publicclassProgressBarActivityextendsAppCompatActivityimplementsView.OnClickListener{
privateintcurrentProgress=0;
privateProgressBarprogressBar;
privateintmaxProgress;
privateHandlermHandler=newHandler(){
@Override
publicvoidhandleMessage(@NonNullMessagemsg) {
super.handleMessage(msg);
switch(msg.what){
case0:
progressBar.setProgress(currentProgress);
break;
? ? ? ? ?? }
? ? ?? }
?? };
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_bar);
progressBar=findViewById(R.id.pb);
maxProgress=progressBar.getMax();
mtu_pb=findViewById(R.id.pb_mtu);
?? }
@Override
protectedvoidonStart() {
super.onStart();
newThread(){
@Override
publicvoidrun() {
while(true){
try{
for(inti=0;i<=100;i++){
Thread.sleep(1000);
currentProgress+=10;
if(currentProgress>maxProgress){
break;
? ? ? ? ? ? ? ? ? ? ? ? ?? }
mHandler.sendEmptyMessage(0);
? ? ? ? ? ? ? ? ? ? ?? }
}catch(InterruptedExceptione){
e.printStackTrace();
? ? ? ? ? ? ? ? ?? }
? ? ? ? ? ? ?? }
? ? ? ? ?? }
}.start();
?? } ? ?
1.可以實現(xiàn)進(jìn)度條的自動加載澎语,運用多線程的相關(guān)知識;
手動:
publicclassProgressBarActivityextendsAppCompatActivityimplementsView.OnClickListener{
privateProgressBarprogressBar_try;
privateButtonmtu_pb;
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_bar);
progressBar_try=findViewById(R.id.pb_try);
mtu_pb.setOnClickListener(this);
}
@Override
publicvoidonClick(Viewview) {
switch(view.getId()){
caseR.id.pb_mtu:
intprogress=progressBar_try.getProgress();
progress+=10;
progressBar_try.setProgress(progress);
break;
default:
break;
? ? ?? }
?? }
}
可以實現(xiàn)進(jìn)度條的手動加載验懊,按動一次按鈕擅羞,就可以實現(xiàn)進(jìn)度條的一次加載,每次加載10%
2.拖動條seekbar
首先在layout布局文件中創(chuàng)建拖動條
<SeekBar
android:id="@+id/sb_norbal"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/txt_cur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:textSize="30sp"/>
<SeekBar
android:id="@+id/sb_custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:maxHeight="10dp"
android:maxWidth="5dp"
android:progressDrawable="@mipmap/fnegmain"
android:thumb="@color/colorPrimary"/>
android:progressDrawable是拖動條的樣式义图,可以放自己喜歡的圖片和背景减俏;android:thumb是拖動后顯示的背景和顏色。
.java文件中歌溉,seekbar點擊事件有三個方法垄懂,第一個是進(jìn)度條改變骑晶,第二個是點擊拖動條,第三個是松開進(jìn)度條
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seek_bar);
mContext=this;
sb_normal=findViewById(R.id.sb_norbal);
sb_custom=findViewById(R.id.sb_custom);
txt_cur=findViewById(R.id.txt_cur);
sb_normal.setOnSeekBarChangeListener(newSeekBar.OnSeekBarChangeListener() {
@Override
//第一個參數(shù)是seekbar的對象草慧,第二個是進(jìn)度條的值桶蛔,第三個是是否進(jìn)度條的值有改變
publicvoidonProgressChanged(SeekBarseekBar,inti,booleanb) {
txt_cur.setText("當(dāng)前進(jìn)度值: "+i+" / 100");
? ? ? ? ?? }
@Override
publicvoidonStartTrackingTouch(SeekBarseekBar) {
Toast.makeText(mContext,"觸碰SeekBar",Toast.LENGTH_SHORT).show();
? ? ? ? ?? }
@Override
publicvoidonStopTrackingTouch(SeekBarseekBar) {
Toast.makeText(mContext,"松開SeekBar",Toast.LENGTH_SHORT).show();
? ? ? ? ?? }
? ? ?? });
?? }
5.RadioGroup && RadioButton
RadioButton 實際上就是一個選框而已,不過如果沒有RadioGroup的存在漫谷,RadioButton可以進(jìn)行多項選擇仔雷,但是如果存在RadioGroup的制約,它就從多選框變成了單選框舔示。
RadioGrouprg=findViewById(R.id.radiugroup);
rg.setOnCheckedChangeListener(newRadioGroup.OnCheckedChangeListener(){
@Override
publicvoidonCheckedChanged(RadioGroupradioGroup,inti) {
switch(i){
caseR.id.button_1:
Log.d("onCheckedChanged","add");
Toast.makeText(ThirdActivity.this,"you clicked add",Toast.LENGTH_LONG).show();
break;
caseR.id.button_2:
Log.d("onCheckedChanged","delete");
Toast.makeText(ThirdActivity.this,"you clicked delete",Toast.LENGTH_LONG).show();
break;
default:
break;
? ? ? ? ? ? ? }
? ? ? ? ? }
? ? ? });
用法和button按鈕的基本一樣碟婆,只是在設(shè)置點擊事件的時候略有不同,自己注意體會惕稻。
RadioGroup && RadioButton的嵌套使用如下:
<RadioGroup
android:id="@+id/radiugroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete"
android:textAllCaps="false"
android:textSize="30sp"
android:id="@+id/button_2">
</RadioButton>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add"
android:textAllCaps="false"
android:textSize="30sp"
android:id="@+id/button_1">
</RadioButton>
</RadioGroup>
6..CheckBoxs復(fù)選框的實際應(yīng)用
CheckBoxs是復(fù)選框竖共,和RadioGroup && RadioButton沒什么太大的區(qū)別
<CheckBox
android:id="@+id/check_basket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="籃球"/>
cb_basket=findViewById(R.id.check_basket);
cb_basket.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener() {
@Override
publicvoidonCheckedChanged(CompoundButtoncompoundButton,booleanb) {
Intentintent=newIntent(ThirdActivity.this,MainActivity.class);
startActivity(intent);
? ? ? ? ? }
? ? ? });
以上代碼就是在實際開發(fā)中對復(fù)選框的運用數(shù)據(jù)類型是boolean類型
7.對話框的實際應(yīng)用
publicclassThirdActivityextendsAppCompatActivityimplementsView.OnClickListener{
Buttonbutton2=findViewById(R.id.button_adalog);
button2.setOnClickListener(this);
@Override
publicvoidonClick(Viewview) {
AlertDialog.Builderbuilder=newAlertDialog.Builder(ThirdActivity.this);
switch(view.getId()){
caseR.id.button_adalog:
builder.setTitle("對話框");
builder.setMessage("今晚喝酒嗎");
builder.setCancelable(false);
builder.setPositiveButton("走",newDialogInterface.OnClickListener() {
@Override
publicvoidonClick(DialogInterfacedialogInterface,inti) {
Toast.makeText(ThirdActivity.this,"你也配喝酒",
Toast.LENGTH_LONG).show();
? ? ? ? ? ? ? ? ?? }
? ? ? ? ? ? ?? });
builder.setNegativeButton("不去,我要敲代碼",newDialogInterface.OnClickListener() {
@Override
publicvoidonClick(DialogInterfacedialogInterface,inti) {
Toast.makeText(ThirdActivity.this,"好小子俺祠!",Toast.LENGTH_LONG).show();
? ? ? ? ? ? ? ? ?? }
? ? ? ? ? ? ?? });
break;
caseR.id.button_adalog2:
builder.setTitle("單選對話框");
builder.setIcon(R.mipmap.ic_launcher);
builder.setSingleChoiceItems(newString[]{
"好的公给,一起吧。","不蜘渣,我要當(dāng)廢物淌铐。","都行"
},0,newDialogInterface.OnClickListener() {
@Override
publicvoidonClick(DialogInterfacedialogInterface,inti) {
Toast.makeText(ThirdActivity.this,"選中的",Toast.LENGTH_SHORT).show();
? ? ? ? ? ? ? ? ?? }
? ? ? ? ? ? ?? });
break;
? ? ?? }
?? }
}
上述代碼是.java文件里面的所屬代碼,首先函數(shù)名不僅僅需要繼承AppCompatActivity,想要使用 AlertDialog,函數(shù)名還要繼承View.OnClickListener接口蔫缸,然后在函數(shù)中覆寫onClick函數(shù)腿准,以此表示按鈕的點擊事件。
在layout 布局文件中拾碌,則是直接創(chuàng)建一個按鈕即可吐葱。
onClick覆寫中,上述代碼使用switch-case語句是因為有單選對話框的存在倦沧,必須要判斷點擊的是那個按鈕唇撬,然后才能實現(xiàn)相關(guān)功。在對應(yīng)的case語句下面編寫其邏輯代碼展融。
8.listview的使用
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fastScrollEnabled="true"
android:id="@+id/lv_main">
</ListView>
首先需要創(chuàng)建一個布局窖认,在里面添加一個listview,寬度高度自己調(diào)整告希,記得控件必須添加一個id
然后在.java文件中添加實現(xiàn)listview的代碼
publicclassListViewTryextendsAppCompatActivity{
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_try);
ListViewlv=findViewById(R.id.lv_main);
lv.setAdapter(newMyListViewAdapter());
?? }
publicclassMyListViewAdapterextendsBaseAdapter{
privateTextViewtv;
@Override
publicintgetCount() {
return100;
? ? ?? }
@Override
publicObjectgetItem(inti) {
returnnull;
? ? ?? }
@Override
publiclonggetItemId(inti) {
return0;
? ? ?? }
@Override
publicViewgetView(inti,Viewview,ViewGroupviewGroup) {
if(view==null){
tv=newTextView(ListViewTry.this);
? ? ? ? ?? }
else{
tv=(TextView)view;
? ? ? ? ?? }
tv.setText("蝌蚪扑浸!"+i);
returntv;
? ? ?? }
?? }
}
上述代碼用來實現(xiàn)listview效果,首先需要找到我們需要的控件ID燕偶,ListView lv = findViewById(R.id.lv_main);完成功能喝噪。然后需要向listview添加數(shù)據(jù),這就需要自己建立一個數(shù)據(jù)類指么,讓他繼承BaseAdapter酝惧,繼承里面的方法榴鼎,第一個方法public int getCount()是用來實現(xiàn)顯示幾行; public View getView方法是用來顯示listview中的文字晚唇。最后lv.setAdapter(new MyListViewAdapter());即可巫财。
9.ScrollView及HorizontalScrollView
<?xmlversion="1.0"encoding="utf-8"?>
<ScrollViewxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Scrollview"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test1"
android:id="@+id/test1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test2"
android:id="@+id/test2"/>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/HScrollview1"
android:text="Htext1"/>
<Button
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/HScrollview2"
android:text="Htext2"/>
</LinearLayout>
</HorizontalScrollView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/text6"
android:text="the last text"
android:layout_marginTop="200dp"/>
</LinearLayout>
</ScrollView>
上述代碼可以知道兩種滾動布局的用法,ScrollView是主布局哩陕,直接作用在布局里面平项,而HorizontalScrollView布局則是作用在ScrollView中,是它的子布局悍及,嵌套在其中闽瓢。前者是垂直布局,后者是水平布局心赶。但是需要注意扣讼,兩種布局下面都要用LinearLayout布局來實現(xiàn),LinearLayout中可以添加控件
10.RecycleView 的使用
1.利用RecycleView實現(xiàn)listview
publicclassLinearRecycleViewActivityextendsAppCompatActivity{
privateRecyclerViewmyrcv;
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear_recycle_view);
myrcv=findViewById(R.id.rv_main);
myrcv.setLayoutManager(newLinearLayoutManager(LinearRecycleViewActivity.this));
myrcv.setAdapter(newLinearAdapter(LinearRecycleViewActivity.this));
?? }
}
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
首先創(chuàng)建一個活動园担,在布局里面添加一個RecycleView届谈。.java文件中找到所用的控件,然后設(shè)置一個布局管理器弯汰,最后設(shè)置一個數(shù)據(jù)適配器。
publicclassLinearAdapterextendsRecyclerView.Adapter<LinearAdapter.LinearViewHolder>{
privateContextmcontext;
publicLinearAdapter(Contextcontext){
this.mcontext=context;
?? }
@NonNull
@Override
publicLinearAdapter.LinearViewHolderonCreateViewHolder(@NonNullViewGroupparent,intviewType) {
returnnewLinearViewHolder(LayoutInflater.from(mcontext).inflate(R.layout.linear_recycle,parent,false));
?? }
@Override
publicvoidonBindViewHolder(@NonNullLinearAdapter.LinearViewHolderholder,finalintposition) {
holder.textview.setText("hello kedou");
holder.itemView.setOnClickListener(newView.OnClickListener() {
@Override
publicvoidonClick(Viewview) {
Toast.makeText(mcontext,"you click the"+position,Toast.LENGTH_SHORT).show();
? ? ? ? ?? }
? ? ?? });
?? }
@Override
publicintgetItemCount() {
return100;
?? }
classLinearViewHolderextendsRecyclerView.ViewHolder{
privateTextViewtextview;
publicLinearViewHolder(ViewitemView){
super(itemView);
textview=itemView.findViewById(R.id.tv_title);
? ? ?? }
?? }
}
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="蝌蚪"
android:id="@+id/tv_title"
android:gravity="center"
android:textSize="20sp"
android:textColor="#000000"
android:background="@drawable/abc_vector_test"/>? ?
首先創(chuàng)建一個布局文件湖雹,此布局文件中添加一個想要在RecycleView中顯示的控件咏闪。在.java文件中,數(shù)據(jù)適配器需要繼承RecycleView的適配器摔吏,然后繼承相關(guān)方法鸽嫂。 onCreateViewHolder方法用來創(chuàng)建一個ViewHolder的實例,onBindViewHolder方法用來綁定布局征讲,可以在里面添加一些邏輯事件(設(shè)置文字据某,顯示彈窗之類的),getItemCount方法用來返回列表的長度诗箍。class LinearViewHolder extends RecyclerView.ViewHolder是用來滿足適配器的泛型事件癣籽。
11Fragment的使用
1.靜態(tài)加載fragment
publicclassMyfragmentextendsFragment{
@Nullable
@Override
publicViewonCreateView(@NonNullLayoutInflaterinflater,@NullableViewGroupcontainer,@NullableBundlesavedInstanceState) {
//第七行代碼是用來加載布局的主要代碼
Viewview=inflater.inflate(R.layout.activity_myfragment,container,false);
returnview;
?? }
}
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:name="com.example.frag1.Fragment.Myfragment"
android:id="@+id/myfragment"
android:layout_width="match_parent"
android:layout_height="300dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="30dp"
android:id="@+id/rl_fragment"/>
</LinearLayout>
靜態(tài)加載碎片,其實是非常簡單的滤祖,首先需要創(chuàng)建一個活動筷狼,這個類必須繼承Fragment。在這個活動下面的布局里面就可以寫想要在碎片中加載的東西匠童,可以在里面添加一些簡單的控件埂材,在.java文件中,需要public View onCreateView方法來實現(xiàn)碎片的加載汤求,具體請看上述代碼俏险。然后在主函數(shù)的布局中添加一個標(biāo)簽fragment严拒,作為容器,直接運行即可加載碎片竖独。
2.動態(tài)加載碎片
首先創(chuàng)建一個活動作為主活動裤唠,在主活動的布局文件中添加一個FragLayout,作為所有碎片的容器预鬓。
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/ly_top_bar"
android:layout_above="@id/div_tab_bar"
android:id="@+id/ly_content1"
android:background="@android:color/transparent">
</FrameLayout>
然后創(chuàng)建其他活動巧骚,在其布局文件中添加自己想要的效果,在其.java文件中重寫View onCreateView方法表示添加布局格二。
主活動需要寫碎片的實現(xiàn):
privatevoidreplacefragemnt(MyFragment_tishimyFragment_tishi){
FragmentManagerfragmentManager=getSupportFragmentManager();
FragmentTransactiontransaction=fragmentManager.beginTransaction();
//尤為重要的是劈彪,第五行的代碼,碎片的被代替布局必須是在主函數(shù)中自己寫的碎片容器顶猜,代替者是代替函數(shù)中活動的對象沧奴。
transaction.replace(R.id.ly_content1,myFragment_tishi);
transaction.commit();
?? }
//下面這串代碼可以添加在邏輯事件中,調(diào)用replace方法长窄,實現(xiàn)碎片的動態(tài)添加
replacefragemnt(newMyFragment_tishi());
* 首先自定義一個代替方法滔吠,是將碎片中原有的事物代替成為一個新的事物(新的事物就是自己寫的幾個活動),然后在點擊事件中調(diào)用自定義的代替方法,碎片的動態(tài)添加就可以完成挠日。
## 3.存儲數(shù)據(jù)
### 1.SharedPreferences數(shù)據(jù)存儲
* ``` java
? Button button2 = findViewById(R.id.button2);
? ? ? ?? button2.setOnClickListener(new View.OnClickListener(){
? ? ? ? ? ?? public void onClick(View v){
? ? ? ? ? ? ? ?? SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
? ? ? ? ? ? ? ?? editor.putString("name","tom");
? ? ? ? ? ? ? ?? editor.putInt("age",20);
? ? ? ? ? ? ? ?? editor.putBoolean("married",false);
? ? ? ? ? ? ? ?? editor.apply();
? ? ? ? ? ?? }
? ? ? ?? });
button按鈕邏輯中實現(xiàn)數(shù)據(jù)的存儲
調(diào)用SharedPreferences對象的edit方法來獲取haredPreferences.Editor對象疮绷,然后向該對象中添加數(shù)據(jù),添加完畢后通過apply方法將數(shù)據(jù)提交嚣潜,完成數(shù)據(jù)的存儲冬骚。
3.數(shù)據(jù)的存儲
1.從SharedPreferences讀取數(shù)據(jù)
此代碼布局文件中使用了chrckBox復(fù)選框記住密碼來實現(xiàn)功能操作。
privateSharedPreferencespref;
privateSharedPreferences.Editoreditor;
privateCheckBoxremember;
Buttonbutton=findViewById(R.id.button);
button.setOnClickListener(newView.OnClickListener() {
@Override
publicvoidonClick(Viewview) {
Stringeditone=edit1.getText().toString();
Stringedittwo=edit2.getText().toString();
if(editone.equals("2373704672")&&edittwo.equals("lxswwy.1314")){
editor=pref.edit();
if(remember.isChecked()){
editor.putBoolean("remember password",true);
editor.putString("account:",editone);
editor.putString("password:",edittwo);
}else{
editor.clear();
? ? ? ? ? ? ? ? ? }
editor.apply();
Intentintent=newIntent(MainActivity.this,FirstActivity.class);
startActivity(intent);
finish();
? ? ? ? ? ? ? }
else{
Toast.makeText(MainActivity.this,"賬號或密碼輸入有誤",Toast.LENGTH_LONG).show();
? ? ? ? ? ? ? }
? ? ? ? ? }
? ? ? });
按鈕中實現(xiàn)自動存入密碼功能
2.數(shù)據(jù)庫SQLIte
SQLiteOpenHelper的其中一個使用比較多的構(gòu)造方法中懂算,里面有四個參數(shù)只冻,第一個是context,第二個是數(shù)據(jù)庫的名字计技,第三個是查詢數(shù)據(jù)時返回一個自定義的Cursor喜德,一般都是傳入null,最后一個是版本號垮媒。
首先新建一個類舍悯,繼承SQLiteOpenHelper
publicclassMyDatabaseHelperextendsSQLiteOpenHelper{
publicstaticfinalStringCREATE_BOOK="create tabke Book("
+"id integer primary key autoincrement,"
+"author text,"
+"price real,"
+"pages integer,"
+"name text)";
privateContextmContext;
publicMyDatabaseHelper(@NullableContextcontext,@NullableStringname,@NullableSQLiteDatabase.CursorFactoryfactory,intversion) {
super(context,name,factory,version);
mContext=context;
?? }
@Override
publicvoidonCreate(SQLiteDatabasesqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_BOOK);
Toast.makeText(mContext,"create successed",Toast.LENGTH_SHORT).show();
?? }
@Override
publicvoidonUpgrade(SQLiteDatabasesqLiteDatabase,intoldVersion,intnewVersion) {
?? }
}
然后在主函數(shù)中加以實現(xiàn)
privateMyDatabaseHelperdbhelper;
dbhelper=newMyDatabaseHelper(this,"BookStore.db",null,1);
Buttonbutton=findViewById(R.id.button_sql);
button.setOnClickListener(newView.OnClickListener() {
@Override
publicvoidonClick(Viewview) {
dbhelper.getWritableDatabase();
? ? ? ? ?? }
? ? ?? });
上述代碼是以按鈕為操作連接,然后實現(xiàn)數(shù)據(jù)庫的創(chuàng)建涣澡。
4.多媒體使用
1.通知的實現(xiàn):
publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener
finalintNOTIFYID=0x123;
privateButtonmybtu;
@RequiresApi(api=Build.VERSION_CODES.JELLY_BEAN)
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mybtu=findViewById(R.id.btu_inform);
mybtu.setOnClickListener(this);
?? }
@RequiresApi(api=Build.VERSION_CODES.JELLY_BEAN)
@Override
publicvoidonClick(Viewview) {
switch(view.getId()){
caseR.id.btu_inform:
finalNotificationManagernotificationManager=
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// 創(chuàng)建一個Notification對象
Notification.Buildernotification=newNotification.Builder(this);
// 設(shè)置打開該通知贱呐,該通知自動消失
notification.setAutoCancel(true);
// 設(shè)置通知的圖標(biāo)
notification.setSmallIcon(R.mipmap.ic_launcher);
// 設(shè)置通知內(nèi)容的標(biāo)題
notification.setContentTitle("哈哈哈哈哈哈");
// 設(shè)置通知內(nèi)容
notification.setContentText("點擊查看詳情!");
//設(shè)置使用系統(tǒng)默認(rèn)的聲音入桂、默認(rèn)震動
notification.setDefaults(Notification.DEFAULT_SOUND
|Notification.DEFAULT_VIBRATE);
//設(shè)置發(fā)送時間
notification.setWhen(System.currentTimeMillis());
// 創(chuàng)建一個啟動其他Activity的Intent
Intentintent=newIntent(MainActivity.this
,DetailActivity.class);
PendingIntentpi=PendingIntent.getActivity(
MainActivity.this,0,intent,0);
//設(shè)置通知欄點擊跳轉(zhuǎn)
notification.setContentIntent(pi);
//發(fā)送通知
notificationManager.notify(NOTIFYID,notification.build());
break;
default:
break;
? ? ?? }
?? }
}
上述代碼已經(jīng)有很明確的注解奄薇,此處不做闡釋。DetailActivity是點擊通知后跳轉(zhuǎn)的頁面.?
2.攝像頭拍照
xml文件:
<?xmlversion="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="take photo"
android:textAllCaps="false">
</Button>
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</ImageView>
</LinearLayout>
// .java文件
publicclassMainActivityextendsAppCompatActivity{
publicstaticfinalintTAKE_PHOTO=1;
privateImageViewPICTURE;
privateUriimageUri;
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtontakePhoto=findViewById(R.id.take_photo);
PICTURE=findViewById(R.id.picture);
takePhoto.setOnClickListener(newView.OnClickListener() {
@Override
publicvoidonClick(Viewview) {
FileoutputImage=newFile(getExternalCacheDir(),"output_image.jpg");
try{
if(outputImage.exists()){
outputImage.delete();
? ? ? ? ? ? ? ? ?? }
outputImage.createNewFile();
}catch(IOExceptione){
e.printStackTrace();
? ? ? ? ? ? ?? }
if(Build.VERSION.SDK_INT>=24){
imageUri=FileProvider.getUriForFile(MainActivity.this,
"com.example.cameraalbumtest.fileprovider",
outputImage);
}else{
imageUri=Uri.fromFile(outputImage);
? ? ? ? ? ? ?? }
//啟動相機(jī)程序
Intentintent=newIntent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,TAKE_PHOTO);
? ? ? ? ?? }
? ? ?? });
?? }
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode,@NullableIntentdata) {
switch(requestCode){
caseTAKE_PHOTO:
if(requestCode==RESULT_OK){
try{
//將拍攝的照片顯示出來
Bitmapbitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
PICTURE.setImageBitmap(bitmap);
}catch(FileNotFoundExceptione){
e.printStackTrace();
? ? ? ? ? ? ? ? ?? }
? ? ? ? ? ? ?? }
break;
default:
break;
? ? ?? }
?? }
}
調(diào)取系統(tǒng)相冊
新增一個方法
publicvoidopenGallery() {
Intentintent=newIntent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,CROP_PHOTO);
?? }
把按鈕的點擊事件改為:
@Override
publicvoidonClick(Viewv) {
switch(v.getId()) {
caseR.id.take_photo:
//openCamera(this);
openGallery();
break;
? ? ?? }
?? }
因為這里請求碼為CROP_PHOTO抗愁,因此對上邊的CROP_PHOTO做些改造
@Override
publicvoidonActivityResult(intrequestCode,intresultCode,Intentdata) {
switch(requestCode) {
caseTAKE_PHOTO:
? ? ? ? ? ? ?? ...
break;
caseCROP_PHOTO:
if(resultCode==RESULT_OK) {
try{
if(data!=null) {
Uriuri=data.getData();
imageUri=uri;
? ? ? ? ? ? ? ? ? ? ?? }
Bitmapbitmap=BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageUri));
picture.setImageBitmap(bitmap);
}catch(FileNotFoundExceptione) {
e.printStackTrace();
? ? ? ? ? ? ? ? ?? }
? ? ? ? ? ? ?? }
break;
default:
super.onActivityResult(requestCode,resultCode,data);
break;
? ? ?? }
?? }