Android開發過程中的坑及解決方法收錄
1.某個控制元件要放在Linearlayout佈局的底部(底部導航條)
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
...>
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="0dp"
android:Layout_weight="2">
...//巢狀的其他佈局……
</LinearLayout>
...//巢狀的其他佈局
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
簡單說明一下,上面的程式碼中有一個Linearlayout,裡面嵌套了兩個Linearlayout
這裡的關鍵是巢狀裡面的第一個Linearlayout佈局,注意這個佈局裡面的這兩行屬性程式碼
`android:layout_height="0dp"`
`android:Layout_weight="2"`
第二個Linearlayout就是可以放在底部的一個Linearlayout(當然你可以寫你自己的佈局)
2.RecyclerView顯示圖片卡頓優化
思路:圖片太多,顯示卡頓的原因主要是因為在RecyclerView滑動的過程中同時載入網路的圖片,所以卡頓。
我們實現滑動的時候不載入網路圖片,當不滑動的時候再載入網路圖片,這樣流暢度就可以提高許多
在RecyclerView的Adapter(自己寫的)中新增一個判斷RecyclerView是否滑動的boolean變數isScrolling
protected boolean isScrolling = false;
public void setScrolling(boolean scrolling) {
isScrolling = scrolling;
}
之後在Adapter裡面的onBindViewHolder方法控制載入圖片
public void onBindViewHolder(ViewHolder holder, int position) {
String url = mlist.get(position).getImg().getUrl();
if (!isScrolling){
//我使用的是Ion顯示圖片框架
//如果不在滑動,則載入網路圖片
Ion.with(holder.imageView.getContext())
.load(url)
.withBitmap()
.placeholder(R.drawable.grey)
.intoImageView(holder.imageView);
}else {
//如果在滑動,就先載入本地的資源圖片
Drawable temp = holder.imageView.getResources().getDrawable(R.drawable.grey, null);
holder.imageView.setImageDrawable(temp);
}
}
在相應的Activity中呼叫RecyclerView的addOnScrollListener方法,設定一個滑動監聽器
mRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) { // 滾動靜止時才載入圖片資源,極大提升流暢度
adapter.setScrolling(false);
adapter.notifyDataSetChanged(); // notify呼叫後onBindViewHolder會響應呼叫
} else{
adapter.setScrolling(true);
}
super.onScrollStateChanged(recyclerView, newState);
}
});
3.ScrollView與RecyclerView滑動衝突
這裡使用NestedScrollView即可,然後設定RecyclerView的NestedScrollingEnabled屬性為false
兩種方法設定RecyclerView的NestedScrollingEnabled屬性
- 呼叫`RecyclerView`的`setNestedScrollingEnabled`方法
- 在xml檔案裡面,把`RecyclerView`直接設定為`flase`
判斷ScrollView是否滑動到底部
給ScrollView新增一個滑動監聽器,然後進行相關處理
mNestedsv.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener(www.michenggw.com) {
public void onScrollChange(www.mingcheng178.com NestedScrollView v, int scrollX,www.trgj888.com int scrollY, int oldScrollX, int oldScrollY) {
View view = mNestedsv.getChildAt(0);
if (mNestedsv.getHeight(www.yongshiyule178.com )+mNestedsv.getScrollY() ==view.getHeight()){
//相關提示
//相關操作
//下拉重新整理,資料更新操作
//...
}
}
});
4.使用okhttp返回資料相同解決方法
看了資料,好像是respone.body().string()只能呼叫一次,還有okhttp是有快取的
使用的情景:有一個API介面,每次訪問改介面,都會返回不同的json資料,但是使用okhttp,每次訪問該API返回的資料都是相同
我的解決方法:
給API請求時新增引數,有些API是可以帶引數的,可以修改引數,達到是不同網址的效果
5.RecyclerView資料更新
呼叫Adapter的notifyDataSetChanged方法即可