編輯:關於 Android 程式設計
使用實現了單選功能的 ListView。不要問為什麼不使用 RecyclerView——就這個需求而言,RecyclerView 真的做得不如 ListView 和 GridView 完善全面,但是 RecyclerView 確實很靈活(目前發現 RecyclerView 有幾個 bug,以後再吐槽),RecyclerView 也有自己的優勢。
這裡解釋一下我們為啥使用了 ListView:ListView 加上 Fragment,點擊 ListView 的 item 來切換 Fragment,Fragment 是可以保存狀態的,使用了 hide 和 show 事務,可以根據下發的數據來創建對面的 Fragment,也就是創建對應的 Fragment 類型。下面先看看圖片吧。



ListView 可以支持多選和單選:
tabList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // 單選
tabList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // 多選
看代碼之前先看一下工程結構。
java 代碼:

xml 文件:

要實現單選,那麼 ListView 的 item 的布局 ViewGroup 需要實現 Checkable 接口。下面是 item_tab_list.xml:
<com.example.bottommenudemo.CheckableRelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/tabName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="4dp"
android:clickable="false"
android:maxLines="1"
android:text="標題欄"
android:textColor="@android:color/white"
android:textSize="15sp" />
<CheckedTextView
android:layout_width="8dip"
android:layout_height="80dp"
android:layout_alignParentRight="true"
android:background="@drawable/checkbox_selector"
android:gravity="center"
android:paddingLeft="8dp" />
</com.example.bottommenudemo.CheckableRelativeLayout>
需要把 CheckedTextView 這個選中 flag 以外的控件設置為 android:clickable="false"。
下面是自定義的 RelativeLayout,主要是實現了 Checkable 接口:
package com.example.bottommenudemo;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.RelativeLayout;
/**
* Created by Danxx on 2016/4/29.
*/
public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
private static final int CHECKABLE_CHILD_INDEX = 1;
private Checkable child;
public CheckableRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
child = (Checkable) getChildAt(CHECKABLE_CHILD_INDEX);
}
@Override
public boolean isChecked() {
return child.isChecked();
}
@Override
public void setChecked(boolean checked) {
child.setChecked(checked);
}
@Override
public void toggle() {
child.toggle();
}
}
ListView 的 choiceMode 可以在代碼中設置,也可以在 xml 文件中設置:
tabList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // 單選(代碼實現)
android:choiceMode="singleChoice" // 單選(xml 中實現)
其余的 ListView 使用跟一般的 ListView 使用是一樣的。這個時候我單擊 ListView 的 item 就可以實現單選功能了。
Fragment 的創建我封裝了一下。FragmentFactory.java 就是用來創建對應的 Fragment,需要傳入 FragmentBean 和與 ListView 對應的 position:
package com.example.bottommenudemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import java.util.HashMap;
/**
* fragment build factory
* Created by Danxx on 2016/4/28.
*/
public class FragmentFactory {
/** fragment 緩存 */
private static HashMap<String, Fragment> fragments = new HashMap<String, Fragment>();
public static Fragment buildFragment(FragmentBean data, int pos) {
Fragment fragment = null;
String id = data.getID();
String name = data.getName();
int position = data.getPosition();
String url = data.getUrl();
fragment = fragments.get(String.valueOf(pos));
if (fragment != null) {
return fragment;
}
if (id.equalsIgnoreCase(Common.BACKGROUND)) {
fragment = new FragmentSetBackground();
} else if (id.equalsIgnoreCase(Common.RECOMMEND)) {
fragment = new FragmentSetRecommend();
} else if (id.equalsIgnoreCase(Common.SCREENSAVER)) {
fragment = new FragmentSetScreensaver();
} else if (id.equalsIgnoreCase(Common.ABOUT)) {
fragment = new FragmentSetAbout();
}
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
bundle.putInt("position", position);
bundle.putString("url", url);
if (fragment != null) {
// 傳遞簡單的參數
fragments.put(String.valueOf(pos), fragment);
fragment.setArguments(bundle);
}
return fragment;
}
}
直接看 MainActivity 的代碼:
package com.example.bottommenudemo;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView tabList;
private List<FragmentBean> fragmentData = new ArrayList<FragmentBean>();
private MyAdapater mAdapter;
private int lastPosition = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2_main);
Log.d("danxx", "onCreate--->");
tabList = (ListView) findViewById(R.id.tabList);
/** 填充假數據,可以根據服務器下發的數據來初始化數據
* (一定得給出模板類型 layout_code) */
FragmentBean backGround = new FragmentBean(Common.BACKGROUND, 0, "背景0",
"https://www.dusa.com/da/index.jsp");
fragmentData.add(backGround);
FragmentBean recommend = new FragmentBean(Common.RECOMMEND, 1, "推薦>1",
"https://www.dusa.com/food/list.jsp");
fragmentData.add(recommend);
FragmentBean screensaver = new FragmentBean(Common.SCREENSAVER, 2, "背景>2",
"https://www.meitu.com/pic/con.jsp");
fragmentData.add(screensaver);
FragmentBean about = new FragmentBean(Common.ABOUT, 3, "關於>3",
"https://www.alibaba.com/good/index.php");
fragmentData.add(about);
FragmentBean backGround2 = new FragmentBean(Common.BACKGROUND, 4, "背景>4",
"https://www.dusa.com/da/index.jsp");
fragmentData.add(backGround2);
FragmentBean about2 = new FragmentBean(Common.ABOUT, 5, "關於>5",
"https://www.alibaba.com/good/index.php");
fragmentData.add(about2);
FragmentBean recommend2 = new FragmentBean(Common.RECOMMEND, 6, "推薦>6",
"https://www.dusa.com/food/list.jsp");
fragmentData.add(recommend2);
FragmentBean screensaver2 = new FragmentBean(Common.SCREENSAVER, 7, "背景>7",
"https://www.meitu.com/pic/con.jsp");
fragmentData.add(screensaver2);
FragmentBean about3 = new FragmentBean(Common.ABOUT, 8, "關於>8",
"https://www.alibaba.com/good/index.php");
fragmentData.add(about3);
mAdapter = new MyAdapater(this, fragmentData);
tabList.setAdapter(mAdapter);
tabList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mAdapter.notifyDataSetChanged();
/** 根據用戶點擊來切換 fragment */
tabList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("danxx", "position-->" + position);
if (lastPosition == position) {
return;
}
if (lastPosition != -1) {
Fragment fromFragment = getSupportFragmentManager()
.findFragmentByTag(String.valueOf(lastPosition));
if (fromFragment == null) {
fromFragment = buildFragment(lastPosition);
}
Fragment toFragment = getSupportFragmentManager()
.findFragmentByTag(String.valueOf(position));
if (toFragment == null) {
toFragment = buildFragment(position);
}
switchContent(fromFragment, lastPosition, toFragment, position);
} else {
/* 第一次顯示 fragment */
getSupportFragmentManager().beginTransaction()
.add(R.id.content,
FragmentFactory.buildFragment(mAdapter.getItemData(position), position),
String.valueOf(position))
.commit();
}
lastPosition = position;
}
});
}
public Fragment buildFragment(int position) {
/** 根據模板類型 layout_code 的不同來創建對應的 fragment */
return FragmentFactory.buildFragment(mAdapter.getItemData(position), position);
}
/**
* 切換顯示的 fragment
*/
public void switchContent(Fragment fromFragment, int fromPos,
Fragment toFragment, int toPos) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!toFragment.isAdded()) {
// 先判斷是否被 add 過
// 隱藏當前的 fragment,add 下一個到 Activity 中
transaction.hide(fromFragment)
.add(R.id.content, toFragment, String.valueOf(toPos))
.commit();
} else {
// 隱藏當前的 fragment,顯示下一個
transaction.hide(fromFragment).show(toFragment).commit();
}
}
class MyAdapater extends BaseAdapter {
private List<FragmentBean> mData;
private Context mContext;
public MyAdapater(Context context, List<FragmentBean> data) {
this.mContext = context;
this.mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
public FragmentBean getItemData(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
/**
* 數據不會很多,所以沒有使用 ViewHolder 復用
*/
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.d("danxx", "getView_position-->" + position);
final View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab_list, null);
TextView tabName = (TextView) view.findViewById(R.id.tabName);
tabName.setText(mData.get(position).getName());
return view;
}
}
}
MainActivity.java 需要留意的就是,我們在切換 Fragment 的時候並沒有把所有的 Fragment 都找到然後 hide 掉,我覺得這樣真的很沒有必要,耗時耗力,還顯得很蠢。我使用了 switchContent 方法來做這個操作:從一個 Fragment 切換到另一個 Fragment,就直接是 hide 現在看到的 Fragment,show 我們需要的 Fragment。這樣我們切換 Fragment 就總是對兩個 Fragment 做處理,是不是簡潔了很多?
/**
* 切換顯示的 fragment
* @param fromFragment 當前顯示的
* @param fromPos
* @param toFragment 即將顯示的
* @param toPos
*/
public void switchContent(Fragment fromFragment, int fromPos,
Fragment toFragment, int toPos) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!toFragment.isAdded()) {
// 先判斷是否被 add 過
transaction.hide(fromFragment)
.add(R.id.content, toFragment, String.valueOf(toPos))
.commit();
// 隱藏當前的 fragment,add 下一個到 Activity 中
} else {
transaction.hide(fromFragment).show(toFragment).commit();
// 隱藏當前的 fragment,顯示下一個
}
}
這樣做的好處是 Fragment 實例被保留下來,用戶切回某一項時的狀態不會丟失,同時每次切換只產生兩次 Fragment 操作,開銷可控。
完整的代碼請看 GitHub:FragmentSwitchDemo。
Android 縱向跑馬燈滾動效果實現
淘寶、京東這類電商 App 裡都能看到跑馬燈效果,今天就把以前項目裡的一個 demo 分享給大家。各位看官,且看效果圖。 先定義一個 Bean 文件,這個實體類主要包含
Android 自定義 View 實作仿 GitHub 的提交活躍表格
說明 本文需要一些基礎知識,如 Canvas、Paint、Path、Rect 等類的基本使用,不熟悉的同學可以先學習相關自定義 View 教程,會有很大幫助。 上圖就是
Android 左右聲道控制:AudioTrack 的立體聲平衡實踐
效果預覽 實現思路 核心用的是 AudioTrack。手機通常只有左右兩個聲道,播放時既可以選擇單聲道,也可以選擇雙聲道(立體聲)。 翻一遍 AudioTrack 的
CoordinatorLayout 使用指南
CoordinatorLayout 是 Material Design 中非常重要的佈局容器,可協調子 View 之間的互動行為。它常被視為增強版 FrameLayout