P2 工程結構介紹
??project和module的區別: project僅僅是專案,手機上看不到,而module是手機上的app

下載gradle

gradle全域組態檔

sdk位置local.properties

引入的模塊setting.gradle

生成apk

src

引入第三方庫build.gradle

資源

虛擬機安裝


P3 TextView1控制元件
常見屬性

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:orientation="vertical">
<TextView
android:id="@+id/tv_one"
android:text="@string/tv_one"
android:textColor="#FF0000FF"
android:textStyle="italic"
android:textSize="50sp"
android:background="#FFFF0000"
android:gravity="center_horizontal"
android:layout_width="200dp"
android:layout_height="200dp"/>
</LinearLayout>
注意 配置值的時候不直接寫數值,而是參考res中values目錄下組態檔,

P4 TextView2
帶陰影的textview

android:shadowColor="#FF000000"
android:shadowRadius="3.0"
android:shadowDx="10.0"
android:shadowDy="10.0"

P5 TextView3
實作跑馬燈效果

<TextView
android:id="@+id/tv_one"
android:text="@string/tv_one"
android:textColor="#FF0000FF"
android:textStyle="italic"
android:textSize="50sp"
android:shadowColor="#FF000000"
android:shadowRadius="3.0"
android:shadowDx="10.0"
android:shadowDy="10.0"
android:background="#FFFFFF"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
android:gravity="center_horizontal"
android:layout_width="200dp"
android:layout_height="200dp">
<requestFocus/>
</TextView>

P6 Button1
令button的background屬性生效
<Button
android:text="按鈕"
android:background="@drawable/ic_launcher_background"
android:layout_width="200dp"
android:layout_height="200dp"/>


background可用自定義selector
android:background="@drawable/button_selector"
button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_normal" android:state_pressed="false"/> <!--按鍵按下時-->
<item android:drawable="@drawable/btn_pressed" android:state_pressed="true"/> <!--按鍵沒有按下時-->
</selector>
btn_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#020c41"></solid> <!--按鍵內部填充-->
<stroke android:width="1dp" android:color="#FFFFFF"></stroke> <!--邊框-->
</shape>
btn_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white"></solid>
<stroke android:width="1dp" android:color="#FFFFFF"></stroke>
</shape>
匯入drawable圖片

顏色選擇器
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#57565D" android:state_pressed="false"/><!--按鍵沒有按下,文字的顏色-->
<item android:color="#FFFFFF" android:state_pressed="true"/><!--按鍵按下時,文字的顏色-->
</selector>
P7 Button事件
//獲得按鈕
Button btn = findViewById(R.id.btn_one);
點擊事件
//點擊事件
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG,"S"); //列印東西
}
});
也可以設定button的onclick屬性
android:onClick=""
長按事件
//長按事件
btn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return false;
}
});
觸摸事件
//觸摸事件
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false; //當回傳true,不會處理其他事件
}
});
P8 EditText

<EditText
android:layout_width="100dp"
android:layout_height="100dp"
android:hint="請輸入日期"
android:inputType="date"
android:drawableBottom="@mipmap/ic_launcher"
android:background="@drawable/ic_launcher_background"
android:paddingLeft="10dp"
/>

P9 ImageView

3、4屬性搭配5屬性使用
<ImageView
android:src="@mipmap/ic_launcher"
android:scaleType="fitStart"
android:maxHeight="500dp"
android:maxWidth="500dp"
android:adjustViewBounds="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
P10 ProgressBar

<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="370dp"
android:layout_height="wrap_content"
android:max="200"
android:progress="150" />

P11 notification
得先創建NotificationManager和Notification



<!--按鈕觸發發送通知-->
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:onClick="sendN"
android:text="@string/sendNotification"/>
新建通知具體訊息的activity
public class NotificationActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("TAG", "onCreate: 進入通知");
}
}
通知所有內容
private NotificationManager manager;
private Notification notification;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//創建通知管理
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//創建通道渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel(
"vashon","測驗通知",NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
//我的訊息具體內容
Intent intent = new Intent(this,NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,0,intent,0);
//創建通知
notification = new NotificationCompat.Builder(this,"vashon")
.setContentTitle("我的通知")
.setContentText("這是通知內容")
.setSmallIcon(R.drawable.ic_launcher_background)//不能是RGB圖
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.timg))//大圖示
.setColor(Color.parseColor("#ff0000")) //小圖示顏色
.setAutoCancel(true) //點擊后取消
.setContentIntent(pendingIntent) //通知具體資訊
.build();
}
public void sendN(View view) {
manager.notify(1,notification);
//manager.cancel(1);取消通知
}

P12 ToolBar

<androidx.appcompat.widget.Toolbar
android:id="@+id/tb"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#ffff00"
app:navigationIcon="@drawable/ic_baseline_arrow_back_24"
app:title="標題"
app:titleTextColor="#ff0000"
app:subtitle="子標題"
app:subtitleTextColor="#00ffff"
app:logo="@drawable/ic_baseline_add_a_photo_24"
app:titleMarginStart="120dp"
/>
居中layout_gravity

P13 AlertDialog


public void dialogClick(View view) {
//新建View區域
View dialogView = getLayoutInflater().inflate(R.layout.dialog_view,null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher)
.setTitle("這是一個對話框")
.setMessage("這是訊息")
.setView(dialogView)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e(TAG, "onClick: 確定" );
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e(TAG, "onClick: 取消" );
}
})
.setNeutralButton("中間", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e(TAG, "onClick: 中間" );
}
})
.create()
.show();
}
P14 PopupWindow

public void popupWindowClick(View view) {
View popupView = getLayoutInflater().inflate(R.layout.popupwindow_view,null);
PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,true);
//popupwindow放在view(button控制元件)下面
popupWindow.setBackgroundDrawable( getResources().getDrawable(R.drawable.timg));
popupWindow.showAsDropDown(view);
}

P15 開發布局 LinearLayout(線性布局)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:gravity="center_vertical"
android:divider="@drawable/ic_baseline_add_a_photo_24"
android:showDividers="middle"
android:dividerPadding="100dp"
>
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#ff0000"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
/>
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#ffff00"
android:layout_weight="1"
/>
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#ff0000"/>
</LinearLayout>
效果:

坑:
weight是對剩下空間進行比重劃分,
P16 RelativeLayout (相對布局)


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="@+id/rtl_yellow"
android:background="#ffff00"
android:layout_width="100dp"
android:layout_centerInParent="true"
android:layout_height="100dp"/>
<RelativeLayout
android:background="#ff0000"
android:layout_toLeftOf="@+id/rtl_yellow"
android:layout_width="100dp"
android:layout_height="100dp"/>
<RelativeLayout
android:background="#ff00ff"
android:layout_marginLeft="200dp"
android:layout_width="100dp"
android:layout_height="100dp"/>
</RelativeLayout>

P17 FrameLayout(幀布局,框架布局)

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
P17 TableLayout(表格布局)

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這種布局,一個控制元件占用一行"
/>
<TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="使用TableRow,元素內控制元件在一行"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="該行前面那個控制元件被隱藏了"
/>
</TableRow>
<TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
/>
</TableRow>
</TableLayout>

P19 GridLayout(網格布局)


<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:columnCount="3"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是1個按鈕"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="0"
android:text="這是2個按鈕"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是3個按鈕"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是4個按鈕"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是5個按鈕"
/>
</GridLayout>

P20 ConstraintLayout(約束布局)
通過拉動圈圈進行約束



P21 ListView
item專案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
listView控制元件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
為listView控制元件的item賦值的Bean類
public class Bean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
為listView控制元件進行賦值操作的adapter類
public class MyAdapter extends BaseAdapter {
//為listView控制元件item賦值的資料
private List<Bean> data;
private Context context;
public MyAdapter(List<Bean> data, Context context) {
this.data = data;
this.context = context;
}
@Override
public int getCount() {
//listView可顯示的item數,顯然時data的長度
return data.size();
}
@Override
public Object getItem(int position) {
//一般固定不變
return position;
}
@Override
public long getItemId(int position) {
return 0 ;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
//listView沒顯示一個item通過該方法獲得item
//拿到item的樣式
if (convertView == null){
viewHolder = new ViewHolder();
//拿到item樣式中的tv
convertView = LayoutInflater.from(context).inflate(R.layout.list_item,parent,false);
viewHolder.textView = convertView.findViewById(R.id.tv);
//將item中的樣式放入到tag中
convertView.setTag(viewHolder);
}else {
//第二次訪問item通過tag獲得item,避免頻繁使用findViewById
viewHolder = (ViewHolder) convertView.getTag();
}
//為item中的tv賦值
viewHolder.textView.setText(data.get(position).getName());
return convertView;
}
private final class ViewHolder{
TextView textView;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < 20; i++) {
Bean bean = new Bean();
bean.setName("vashon" + i);
data.add(bean);
}
//獲得ListView
ListView listView = findViewById(R.id.lv);
//listView設定為item賦值的adapter
listView.setAdapter(new MyAdapter(data, this));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("vashon","click" + position);
}
});
}

P22 RecyclerView
需要導包
在專案的build.gradle
// 匯入RecyclerView的依賴包
implementation 'androidx.recyclerview:recyclerview:1.0.0'
item布局樣式
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
recyclerView控制元件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
為listView控制元件的item賦值的Bean類
public class Bean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
為RecyclerView控制元件進行賦值操作的adapter類
public class MyAdapter_RV extends RecyclerView.Adapter<MyAdapter_RV.MyViewHolder> {
//item資料
private List<Bean> data;
private Context context;
public MyAdapter_RV(List<Bean> data, Context context) {
this.data = data;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//1.獲得item布局樣式
View view = View.inflate(context,R.layout.recyclerview_item,null);
//3.回傳item布局中的textView
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
//4.為item系結textView中的資料
holder.tv.setText(data.get(position).getName());
}
@Override
public int getItemCount() {
return data == null ? 0 : data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
//2.獲得布局item樣式中的textView
private TextView tv;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
//2.
tv = itemView.findViewById(R.id.tv);
//2_2創建點擊事件
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener !=null){
mOnItemClickListener.onRecyclerItemClick(getAdapterPosition());
}
}
});
}
}
//設定點擊事件
//----------------------------------------------------------------------------
private OnRecyclerItemClickListener mOnItemClickListener;
//2_1生成listener
public void setmOnItemClickListener(OnRecyclerItemClickListener mOnItemClickListener) {
this.mOnItemClickListener = mOnItemClickListener;
}
//介面
public interface OnRecyclerItemClickListener{
void onRecyclerItemClick(int position);
}
}
//1.獲得RecyclerView
RecyclerView recyclerView = findViewById(R.id.rv);
//2.設定布局
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
//3.設定可設定item的adapter
MyAdapter_RV myAdapter_rv = new MyAdapter_RV(data,this);
recyclerView.setAdapter(myAdapter_rv);
//設定點擊事件
myAdapter_rv.setmOnItemClickListener(new MyAdapter_RV.OnRecyclerItemClickListener() {
@Override
public void onRecyclerItemClick(int position) {
Log.e(TAG, "onRecyclerItemClick: "+position );
}
});
P23 幀影片
放置圖片作為影片的xml檔案,
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_baseline_add_a_photo_24" android:duration="1000"/>
<item android:drawable="@drawable/ic_baseline_arrow_back_24" android:duration="1000"/>
</animation-list>
使用xml檔案
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/ly"
android:background="@drawable/frame"
>
影片開啟
LinearLayout linearLayout = findViewById(R.id.ly);
AnimationDrawable anim = (AnimationDrawable) linearLayout.getBackground();
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flag){
anim.start();
flag = false;
}else {
anim.stop();
flag = true;
}
}
});
效果:圖片不斷切換
P24 補間影片

用實作影片的圖片
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="300dp"
android:maxHeight="300dp"
android:src="@drawable/ic_baseline_arrow_back_24"/>
新建anim檔案,創建實作影片的xml檔案
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000"
/>
</set>
ImageView iv = findViewById(R.id.iv);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//通過加載xml影片設定檔案創建一個Animation物件
Animation animation = AnimationUtils.loadAnimation(
MainActivity.this,R.anim.alpha);
//啟動影片
iv.startAnimation(animation);
}
});
效果:圖片由透明逐漸顯示出來
P25 屬性影片
改變值

可以使用影片的值設定控制元件的某些屬性
ValueAnimator anim = ValueAnimator.ofFloat(0f,1f);
anim.setDuration(2000);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
Log.e(TAG, "onAnimationUpdate: " + value );
}
});
//啟動影片
anim.start();
繼承ValueAnimator直接對控制元件進行操作

上列代碼,對控制元件textView的透明度進行值得變化,
TextView textView = findViewById(R.id.tv);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(textView,"alpha",0f,1f);
objectAnimator.setDuration(4000);
objectAnimator.start();

//設定影片監聽
objectAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
objectAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
}
});
P26 單位和尺寸



layoutParams在java代碼中會使用到,
LinearLayout linearLayout = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(layoutParams);
TextView textView1 = new TextView(this);
textView1.setText("我是文本");
LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams
(300,300);
linearLayout.addView(textView1);
P27 ViewPager

<androidx.viewpager.widget.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
java中設定viewPager
//View集合
LayoutInflater lf = getLayoutInflater().from(this);
View view1 = lf.inflate(R.layout.dialog_view, null);
View view2 = lf.inflate(R.layout.popupwindow_view,null);
List<View> viewList = new ArrayList<>();
viewList.add(view1);
viewList.add(view2);
//viewPager設定adapter
ViewPager viewPager = findViewById(R.id.vp);
MyAdapter_VP myAdapter_vp = new MyAdapter_VP(viewList);
viewPager.setAdapter(myAdapter_vp);
viewPager的adapter
public class MyAdapter_VP extends PagerAdapter {
private List<View> mListView;
public MyAdapter_VP(List<View> mListView) {
this.mListView = mListView;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
container.addView(mListView.get(position),0);
return mListView.get(position);
}
@Override
public int getCount() {
//view的個數
return mListView.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView(mListView.get(position));
}
}
有頁面滑動效果
P28 Fragment

P29 什么是Fragment

可以在同一activity中使用fragment
一個fragment可以復用
可以看作子activity
P30 使用Fragment
創建fragment java檔案
跟Mainactivty差不多都有java檔案和xml檔案
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=".BlankFragment1">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="@string/hello_blank_fragment" />
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:text="button"
android:layout_height="40dp"/>
</LinearLayout>
java檔案
public class BlankFragment1 extends Fragment {
private View root;
private TextView textView;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (root ==null)
root = inflater.inflate(R.layout.fragment_blank1, container, false);
textView = root.findViewById(R.id.tv);
button = root.findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText("click");
}
});
return root;
}
}
activity_main中使用fragment
<fragment android:name="com.example.myapplication.BlankFragment1"
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
P32 動態添加fragment
新建兩個fragment

mainactivity繼承點擊介面,并撰寫切換fragment事件
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = findViewById(R.id.btn);
btn1.setOnClickListener(this);
Button btn2 = findViewById(R.id.btn_2);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn:
replaceFragment(new BlankFragment1());
break;
case R.id.btn_2:
replaceFragment(new ItemFragment());
break;
}
}
//切換fragment
private void replaceFragment(Fragment fragment) {
//開啟事務
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.framelayout,fragment);
transaction.addToBackStack(null);//將fragment加入堆疊中
transaction.commit();
}
}

P33 Activity與fragment通信
通過bundle,
fragment類中有bundle變數,在activity中創建fragment時可以將值放到該變數(bundle)中

代碼如下:
public void onClick(View v) {
switch (v.getId()){
case R.id.btn:
Bundle bundle =new Bundle();
bundle.putString("message","我喜歡享課堂");
BlankFragment1 bf = new BlankFragment1();
//通過bundle通信,
bf.setArguments(bundle);
replaceFragment(bf);
break;
case R.id.btn_2:
replaceFragment(new ItemFragment());
break;
}
}
P35 Fragment和activity的介面通信方案
fragment、activity、介面三者關系

首先定義一個介面
public interface IFragmentCallback {
//發送資訊給activity
void sendMsgToActivity(String msg);
//從activity得到資訊
String getMsgFromActivity();
}
在fragment中定義介面變數并定義get和set方法
在activity中為fragment賦值
case R.id.btn:
Bundle bundle =new Bundle();
bundle.putString("message","我喜歡享課堂");
BlankFragment1 bf = new BlankFragment1();
bf.setArguments(bundle);
//利用介面傳遞資料
bf.setiFragmentCallback(new IFragmentCallback() {
@Override
public void sendMsgToActivity(String msg) {
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
@Override
public String getMsgFromActivity() {
return "hello, I'm from activity";
}
});
replaceFragment(bf);
break;
fragment中設定點擊事件實作資料傳遞
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (root ==null)
root = inflater.inflate(R.layout.fragment_blank1, container, false);
textView = root.findViewById(R.id.tv);
//向activity發送資訊
button = root.findViewById(R.id.btn_3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iFragmentCallback.sendMsgToActivity("hello,I'm from fragment");
}
});
///從activity中獲得資訊
button2 = root.findViewById(R.id.btn_4);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = iFragmentCallback.getMsgFromActivity();
Toast.makeText(BlankFragment1.this.getContext(),msg,Toast.LENGTH_SHORT).show();
}
});
return root;
}
封裝好的介面有:eventBus、LiveData
P36 Fragment生命周期
fragment的執行依托于activity
這些回呼方法在fragment類中可以看到,


P39 ViewPager2的基本使用
引入依賴:(可以在maven倉庫中查找)
implementation group: 'androidx.viewpager2', name: 'viewpager2', version: '1.0.0'
viewPager2控制元件系結adapter
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager2 viewPager2 = findViewById(R.id.viewPager2);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter();
viewPager2.setAdapter(viewPagerAdapter);
}
}
自定義adapter(ViewPagerAdapter)
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewPagerViewHolder> {
private List<String> titles = new ArrayList<>();
public ViewPagerAdapter() {
titles.add("hello");
titles.add("world");
}
@NonNull
@Override
//系結viewPager的view
public ViewPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewPagerViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pager,parent,false));
}
@Override
public void onBindViewHolder(@NonNull ViewPagerViewHolder holder, int position) {
//滑動效果
holder.mTv.setText(titles.get(position));
}
@Override
public int getItemCount() {
//滑動頁面的數量
return 2;
}
//自定義viewHolder
class ViewPagerViewHolder extends RecyclerView.ViewHolder{
TextView mTv;
RelativeLayout mContainer;
public ViewPagerViewHolder(@NonNull View itemView) {
super(itemView);
mContainer = itemView.findViewById(R.id.container);
mTv = mContainer.findViewById(R.id.tvTitle);
}
}
}
item_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvTitle"
android:layout_centerInParent="true"
android:textSize="32dp"
android:text="hello"/>
</RelativeLayout>
P41 ViewPager和Fragment合集
viewPager專門的adapter
FragmentPagerAdapter或者FragmentStateAdapter
MyFragmentPagerAdapter.java
public class MyFragmentPagerAdapter extends FragmentStateAdapter {
List<Fragment> fragmentList =new ArrayList<>();
public MyFragmentPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle,
List<Fragment> fragments) {
super(fragmentManager, lifecycle);
this.fragmentList = fragments;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
}
待使用的fragment
public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_Text = "param1";
// TODO: Rename and change types of parameters
private String mTextString;
View rootView;
public BlankFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1) {
//生成fragment時同時設定mTextString的值
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_Text, param1);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTextString = getArguments().getString(ARG_Text);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView ==null)
rootView = inflater.inflate(R.layout.fragment_blank, container, false);
initView();
return rootView;
}
private void initView() {
//將textView的文本設定為mTextString,在新建fragment時會設定該值
TextView textView = rootView.findViewById(R.id.text);
textView.setText(mTextString);
}
}
activity中設定viewPager2
private void initPager() {
viewPager = findViewById(R.id.viewPager2);
ArrayList<Fragment> fragments = new ArrayList<>();
fragments.add(BlankFragment.newInstance("微信聊天"));
fragments.add(BlankFragment.newInstance("通訊錄"));
fragments.add(BlankFragment.newInstance("發現"));
fragments.add(BlankFragment.newInstance("我"));
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),getLifecycle(),fragments);
viewPager.setAdapter(pagerAdapter);
}
42 ViewPager + Fragment模擬微信首頁
承接上節
撰寫viewpage滑動代碼
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
changeTable(position);
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
撰寫點擊事件圖示點擊事件
private void changeTable(int position) {
ivCurrent.setSelected(false);
switch (position){
//點擊微信圖示,切換fragment的內容
case R.id.id_tab_weixin:
viewPager.setCurrentItem(0);
case 0:
//滑動fragment,改變圖示
ivChat.setSelected(true);
ivCurrent = ivChat;
break;
case R.id.id_tab_call:
viewPager.setCurrentItem(1);
case 1:
ivCall.setSelected(true);
ivCurrent = ivCall;
break;
case R.id.id_tab_find:
viewPager.setCurrentItem(2);
case 2:
ivFind.setSelected(true);
ivCurrent = ivFind;
break;
case R.id.id_tab_me:
viewPager.setCurrentItem(3);
case 3:
ivProfile.setSelected(true);
ivCurrent = ivProfile;
break;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/293210.html
標籤:其他
