Android常用开源项目(二十四)

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

1.先看效果图

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

首页面

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

添加菜单

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

动画显示效果

2.具体实现方式

(1).代码结构图

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

代码结构图

(2).自定义实现Application

public class MyApp extends Application {

private static MyApp mAppApplication;

private SQLHelper sqlHelper;

@Override

public void onCreate() {

super.onCreate();

mAppApplication = this;

}

/**

* 获取Application

*/

public static MyApp getApp() {

return mAppApplication;

}

/**

* 获取数据库Helper

*/

public SQLHelper getSQLHelper() {

if (sqlHelper == null)

sqlHelper = new SQLHelper(mAppApplication);

return sqlHelper;

}

}

(3).实现Activity包下面的类

MainActivity.java

public class MainActivity extends AppCompatActivity {

public static boolean isChange = false;

/** 用户选择的新闻分类列表 */

protected static ArrayList<ChannelItem> userChannelLists;

protected LinearLayout mRadioGroup_content;

private ArrayList<Fragment> fragments;

protected ColumnHorizontalScrollView mColumnHorizontalScrollView;

protected ImageView shade_left;

protected ImageView shade_right;

protected LinearLayout ll_more_columns;

protected RelativeLayout rl_column;

protected ViewPager mViewPager;

/** 屏幕宽度 */

private int mScreenWidth = 0;

/** Item宽度 */

private int mItemWidth = 0;

/** 当前选中的栏目 */

private int columnSelectIndex = 0;

private NewsFragmentPagerAdapter mAdapetr;

private Fragment newfragment;

public final static int CHANNELREQUEST = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

initView();

initData();

initViewPager();

setChangelView();

}

private void initView(){

mRadioGroup_content=(LinearLayout)findViewById(R.id.mRadioGroup_content);

mColumnHorizontalScrollView=(ColumnHorizontalScrollView)findViewById(R.id.mColumnHorizontalScrollView);

shade_left=(ImageView)findViewById(R.id.shade_left);

shade_right=(ImageView)findViewById(R.id.shade_right);

ll_more_columns=(LinearLayout)findViewById(R.id.ll_more_columns);

rl_column=(RelativeLayout)findViewById(R.id.rl_column);

mViewPager=(ViewPager)findViewById(R.id.mViewPager);

}

private void initData(){

mScreenWidth = BaseTools.getWindowsWidth(this);

mItemWidth = mScreenWidth / 7;// 一个Item宽度为屏幕的1/7

userChannelLists = new ArrayList<ChannelItem>();

fragments = new ArrayList<Fragment>();

}

private void initViewPager() {

mAdapetr = new NewsFragmentPagerAdapter(

getSupportFragmentManager());

mViewPager.setOffscreenPageLimit(1);

mViewPager.setAdapter(mAdapetr);

mViewPager.setOnPageChangeListener(pageListener);

}

protected void onMoreColumns(View view) {

startActivityForResult(new Intent(this,ChannelActivity.class),CHANNELREQUEST);

}

public ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() {

@Override

public void onPageScrollStateChanged(int arg0) {

}

@Override

public void onPageScrolled(int arg0, float arg1, int arg2) {

}

@Override

public void onPageSelected(int position) {

mViewPager.setCurrentItem(position);

selectTab(position);

}

};

/**

* 选择的Column里面的Tab

*/

private void selectTab(int tab_postion) {

columnSelectIndex = tab_postion;

for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {

View checkView = mRadioGroup_content.getChildAt(tab_postion);

int k = checkView.getMeasuredWidth();

int l = checkView.getLeft();

int i2 = l + k / 2 - mScreenWidth / 2;

// rg_nav_content.getParent()).smoothScrollTo(i2, 0);

mColumnHorizontalScrollView.smoothScrollTo(i2, 0);

// mColumnHorizontalScrollView.smoothScrollTo((position - 2) *

// mItemWidth , 0);

}

// 判断是否选中

for (int j = 0; j < mRadioGroup_content.getChildCount(); j++) {

View checkView = mRadioGroup_content.getChildAt(j);

boolean ischeck;

if (j == tab_postion) {

ischeck = true;

} else {

ischeck = false;

}

checkView.setSelected(ischeck);

}

}

/**

* 当栏目项发生变化时候调用

*/

public void setChangelView() {

initColumnData();

}

/** 获取Column栏目 数据 */

private void initColumnData() {

userChannelLists = ((ArrayList<ChannelItem>) ChannelManage.getManage(

MyApp.getApp().getSQLHelper()).getUserChannel());

initTabColumn();

initFragment();

}

/**

* 初始化Column栏目项

*/

private void initTabColumn() {

mRadioGroup_content.removeAllViews();

int count = userChannelLists.size();

mColumnHorizontalScrollView.setParam(this, mScreenWidth, mRadioGroup_content, shade_left,

shade_right, ll_more_columns, rl_column);

for (int i = 0; i < count; i++) {

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mItemWidth,

LinearLayout.LayoutParams.WRAP_CONTENT);

params.leftMargin = 5;

params.rightMargin = 5;

// TextView localTextView = (TextView)

// mInflater.inflate(R.layout.column_radio_item, null);

TextView columnTextView = new TextView(this);

columnTextView.setTextAppearance(this, R.style.top_category_scroll_view_item_text);

// localTextView.setBackground(getResources().getDrawable(R.drawable.top_category_scroll_text_view_bg));

columnTextView.setBackgroundResource(R.drawable.radio_buttong_bg);

columnTextView.setGravity(Gravity.CENTER);

columnTextView.setPadding(5, 5, 5, 5);

columnTextView.setId(i);

columnTextView.setText(userChannelLists.get(i).getName());

columnTextView.setTextColor(getResources().getColorStateList(

R.color.top_category_scroll_text_color_day));

if (columnSelectIndex == i) {

columnTextView.setSelected(true);

}

columnTextView.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {

View localView = mRadioGroup_content.getChildAt(i);

if (localView != v)

localView.setSelected(false);

else {

localView.setSelected(true);

mViewPager.setCurrentItem(i);

}

}

}

});

mRadioGroup_content.addView(columnTextView, i, params);

}

}

/**

* 初始化Fragment

*/

private void initFragment() {

fragments.clear();

int count = userChannelLists.size();

for (int i = 0; i < count; i++) {

// Bundle data = new Bundle();

String nameString = userChannelLists.get(i).getName();

// data.putString("text", nameString);

// data.putInt("id", userChannelList.get(i).getId());

// initFragment(nameString);

// map.put(nameString, nameString);

// newfragment.setArguments(data);

fragments.add(initFragment(nameString));

// fragments.add(nameString);

}

mAdapetr.appendList(fragments);

}

public Fragment initFragment(String channelName) {

if (channelName.equals("头条")) {

newfragment = new DemoFragment();

} else if (channelName.equals("足球")) {

newfragment = new DemoFragment();

} else if (channelName.equals("娱乐")) {

newfragment = new DemoFragment();

} else if (channelName.equals("体育")) {

newfragment = new DemoFragment();

} else if (channelName.equals("财经")) {

newfragment = new DemoFragment();

} else if (channelName.equals("科技")) {

newfragment = new DemoFragment();

} else if (channelName.equals("电影")) {

newfragment = new DemoFragment();

} else if (channelName.equals("汽车")) {

newfragment = new DemoFragment();

} else if (channelName.equals("笑话")) {

newfragment = new DemoFragment();

} else if (channelName.equals("时尚")) {

newfragment = new DemoFragment();

} else if (channelName.equals("北京")) {

newfragment = new DemoFragment();

} else if (channelName.equals("军事")) {

newfragment = new DemoFragment();

} else if (channelName.equals("房产")) {

newfragment = new DemoFragment();

} else if (channelName.equals("游戏")) {

newfragment = new DemoFragment();

} else if (channelName.equals("情感")) {

newfragment = new DemoFragment();

} else if (channelName.equals("精选")) {

newfragment = new DemoFragment();

} else if (channelName.equals("电台")) {

newfragment = new DemoFragment();

} else if (channelName.equals("图片")) {

newfragment = new DemoFragment();

} else if (channelName.equals("NBA")) {

newfragment = new DemoFragment();

} else if (channelName.equals("数码")) {

newfragment = new DemoFragment();

} else if (channelName.equals("移动")) {

newfragment = new DemoFragment();

} else if (channelName.equals("彩票")) {

newfragment = new DemoFragment();

} else if (channelName.equals("教育")) {

newfragment = new DemoFragment();

} else if (channelName.equals("论坛")) {

newfragment = new DemoFragment();

} else if (channelName.equals("旅游")) {

newfragment = new DemoFragment();

} else if (channelName.equals("手机")) {

newfragment = new DemoFragment();

} else if (channelName.equals("博客")) {

newfragment = new DemoFragment();

} else if (channelName.equals("社会")) {

newfragment = new DemoFragment();

} else if (channelName.equals("家居")) {

newfragment = new DemoFragment();

} else if (channelName.equals("暴雪")) {

newfragment = new DemoFragment();

} else if (channelName.equals("亲子")) {

newfragment = new DemoFragment();

} else if (channelName.equals("CBA")) {

newfragment = new DemoFragment();

}

return newfragment;

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

try {

if (isChange) {

setChangelView();

// initColumnData();

// initTabColumn();

isChange = false;

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

ChannelActivity.java

public class ChannelActivity extends Activity implements OnItemClickListener {

public static String TAG = "ChannelActivity";

/** 用户栏目的GRIDVIEW */

private DragGrid userGridView;

/** 其它栏目的GRIDVIEW */

private OtherGridView otherGridView;

/** 用户栏目对应的适配器,可以拖动 */

DragAdapter userAdapter;

/** 其它栏目对应的适配器 */

OtherAdapter otherAdapter;

/** 其它栏目列表 */

ArrayList<ChannelItem> otherChannelList = new ArrayList<ChannelItem>();

/** 用户栏目列表 */

ArrayList<ChannelItem> userChannelList = new ArrayList<ChannelItem>();

/** 是否在移动,由于这边是动画结束后才进行的数据更替,设置这个限制为了避免操作太频繁造成的数据错乱。 */

boolean isMove = false;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.channel);

try {

initView();

initData();

} catch (Exception e) {

e.printStackTrace();

}

}

/** 初始化布局 */

void initView() {

userGridView = (DragGrid) findViewById(R.id.userGridView);

otherGridView = (OtherGridView) findViewById(R.id.otherGridView);

TextView tv_title = (TextView)findViewById(R.id.actionbar_title);

tv_title.setText(getResources().getString(R.string.subscribe_my_category));

Button bt_back = (Button)findViewById(R.id.btn_title_back);

bt_back.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

finish();

}

});

}

/** 初始化数据 */

void initData() {

userChannelList = ((ArrayList<ChannelItem>) ChannelManage.getManage(

MyApp.getApp().getSQLHelper()).getUserChannel());

otherChannelList = ((ArrayList<ChannelItem>) ChannelManage.getManage(

MyApp.getApp().getSQLHelper()).getOtherChannel());

setData();

}

void setData() {

userAdapter = new DragAdapter(this, userChannelList);

userGridView.setAdapter(userAdapter);

otherAdapter = new OtherAdapter(this, otherChannelList);

otherGridView.setAdapter(otherAdapter);

// 设置GRIDVIEW的ITEM的点击监听

otherGridView.setOnItemClickListener(this);

userGridView.setOnItemClickListener(this);

}

/** GRIDVIEW对应的ITEM点击监听接口 */

@Override

public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {

// 如果点击的时候,之前动画还没结束,那么就让点击事件无效

if (isMove) {

return;

}

switch (parent.getId()) {

case R.id.userGridView:

// position为 0,1 的不可以进行任何操作

if (position != 0 && position != 1) {

final ImageView moveImageView = getView(view);

if (moveImageView != null) {

TextView newTextView = (TextView) view.findViewById(R.id.text_item);

final int[] startLocation = new int[2];

newTextView.getLocationInWindow(startLocation);

final ChannelItem channel = ((DragAdapter) parent.getAdapter())

.getItem(position);// 获取点击的频道内容

otherAdapter.setVisible(false);

// 添加到最后一个

otherAdapter.addItem(channel);

new Handler().postDelayed(new Runnable() {

@Override

public void run() {

try {

int[] endLocation = new int[2];

// 获取终点的坐标

otherGridView

.getChildAt(otherGridView.getLastVisiblePosition())

.getLocationInWindow(endLocation);

moveAnim(moveImageView, startLocation, endLocation, channel,

userGridView);

userAdapter.setRemove(position);

ChannelManage.getManage(MyApp.getApp().getSQLHelper())

.updateChannel(

channel, "0");

} catch (Exception localException) {

}

}

}, 50L);

}

}

break;

case R.id.otherGridView:

final ImageView moveImageView = getView(view);

if (moveImageView != null) {

TextView newTextView = (TextView) view.findViewById(R.id.text_item);

final int[] startLocation = new int[2];

newTextView.getLocationInWindow(startLocation);

final ChannelItem channel = ((OtherAdapter) parent.getAdapter())

.getItem(position);

userAdapter.setVisible(false);

// 添加到最后一个

userAdapter.addItem(channel);

new Handler().postDelayed(new Runnable() {

@Override

public void run() {

try {

int[] endLocation = new int[2];

// 获取终点的坐标

userGridView.getChildAt(userGridView.getLastVisiblePosition())

.getLocationInWindow(endLocation);

moveAnim(moveImageView, startLocation, endLocation, channel,

otherGridView);

otherAdapter.setRemove(position);

ChannelManage.getManage(MyApp.getApp().getSQLHelper()).updateChannel(

channel, "1");

} catch (Exception localException) {

}

}

}, 50L);

}

break;

default:

break;

}

}

/**

* 点击ITEM移动动画

*

* @param moveView

* @param startLocation

* @param endLocation

* @param moveChannel

* @param clickGridView

*/

private void moveAnim(View moveView, int[] startLocation, int[] endLocation,

final ChannelItem moveChannel,

final GridView clickGridView) {

// 将当前栏目增加到改变过的listview中 若栏目已经存在删除点,不存在添加进去

int[] initLocation = new int[2];

// 获取传递过来的VIEW的坐标

moveView.getLocationInWindow(initLocation);

// 得到要移动的VIEW,并放入对应的容器中

final ViewGroup moveViewGroup = getMoveViewGroup();

final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);

// 创建移动动画

TranslateAnimation moveAnimation = new TranslateAnimation(

startLocation[0], endLocation[0], startLocation[1],

endLocation[1]);

moveAnimation.setDuration(300L);// 动画时间

// 动画配置

AnimationSet moveAnimationSet = new AnimationSet(true);

moveAnimationSet.setFillAfter(false);// 动画效果执行完毕后,View对象不保留在终止的位置

moveAnimationSet.addAnimation(moveAnimation);

mMoveView.startAnimation(moveAnimationSet);

moveAnimationSet.setAnimationListener(new AnimationListener() {

@Override

public void onAnimationStart(Animation animation) {

isMove = true;

}

@Override

public void onAnimationRepeat(Animation animation) {

}

@Override

public void onAnimationEnd(Animation animation) {

moveViewGroup.removeView(mMoveView);

// instanceof 方法判断2边实例是不是一样,判断点击的是DragGrid还是OtherGridView

if (clickGridView instanceof DragGrid) {

otherAdapter.setVisible(true);

otherAdapter.notifyDataSetChanged();

userAdapter.remove();

} else {

userAdapter.setVisible(true);

userAdapter.notifyDataSetChanged();

otherAdapter.remove();

}

isMove = false;

}

});

}

/**

* 获取移动的VIEW,放入对应ViewGroup布局容器

*

* @param viewGroup

* @param view

* @param initLocation

* @return

*/

private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {

int x = initLocation[0];

int y = initLocation[1];

viewGroup.addView(view);

LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(

LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

mLayoutParams.leftMargin = x;

mLayoutParams.topMargin = y;

view.setLayoutParams(mLayoutParams);

return view;

}

/**

* 创建移动的ITEM对应的ViewGroup布局容器

*/

private ViewGroup getMoveViewGroup() {

ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();

LinearLayout moveLinearLayout = new LinearLayout(this);

moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,

LayoutParams.MATCH_PARENT));

moveViewGroup.addView(moveLinearLayout);

return moveLinearLayout;

}

/**

* 获取点击的Item的对应View,

*

* @param view

* @return

*/

private ImageView getView(View view) {

view.destroyDrawingCache();

view.setDrawingCacheEnabled(true);

Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());

view.setDrawingCacheEnabled(false);

ImageView iv = new ImageView(this);

iv.setImageBitmap(cache);

return iv;

}

/** 退出时候保存选择后数据库的设置 */

void saveChannel() {

ChannelManage.getManage(MyApp.getApp().getSQLHelper()).deleteAllChannel();

ChannelManage.getManage(MyApp.getApp().getSQLHelper()).saveUserChannel(

userAdapter.getChannnelLst());

ChannelManage.getManage(MyApp.getApp().getSQLHelper()).saveOtherChannel(

otherAdapter.getChannnelLst());

}

@Override

public void onResume() {

super.onResume();

}

@Override

public void onPause() {

super.onPause();

}

@Override

public void finish() {

super.finish();

if (userAdapter.isListChanged()) {

MainActivity.isChange = true;

// saveChannel();

Log.d(TAG, "数据发生改变");

}

}

}

(4).实现Adapter包下面的类

DragAdapter.java

public class DragAdapter extends BaseAdapter {

/** TAG */

private final static String TAG = "DragAdapter";

/** 是否显示底部的ITEM */

private boolean isItemShow = false;

private final Context context;

/** 控制的postion */

private int holdPosition;

/** 是否改变 */

private boolean isChanged = false;

/** 列表数据是否改变 */

private boolean isListChanged = false;

/** 是否可见 */

boolean isVisible = true;

/** 可以拖动的列表(即用户选择的频道列表) */

public List<ChannelItem> channelList;

/** TextView 频道内容 */

private TextView item_text;

/** 要删除的position */

public int remove_position = -1;

public DragAdapter(Context context, List<ChannelItem> channelList) {

this.context = context;

this.channelList = channelList;

}

@Override

public int getCount() {

return channelList == null ? 0 : channelList.size();

}

@Override

public ChannelItem getItem(int position) {

if (channelList != null && channelList.size() != 0) {

return channelList.get(position);

}

return null;

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

View view = LayoutInflater.from(context).inflate(R.layout.channel_item, null);

item_text = (TextView) view.findViewById(R.id.text_item);

ChannelItem channel = getItem(position);

item_text.setText(channel.getName());

if ((position == 0) || (position == 1)) {

// item_text.setTextColor(context.getResources().getColor(R.color.black));

item_text.setEnabled(false);

}

if (isChanged && (position == holdPosition) && !isItemShow) {

item_text.setText("");

item_text.setSelected(true);

item_text.setEnabled(true);

isChanged = false;

}

if (!isVisible && (position == -1 + channelList.size())) {

item_text.setText("");

item_text.setSelected(true);

item_text.setEnabled(true);

}

if (remove_position == position) {

item_text.setText("");

}

return view;

}

/** 添加频道列表 */

public void addItem(ChannelItem channel) {

channelList.add(channel);

isListChanged = true;

notifyDataSetChanged();

}

/** 拖动变更频道排序 */

public void exchange(int dragPostion, int dropPostion) {

holdPosition = dropPostion;

ChannelItem dragItem = getItem(dragPostion);

Log.d(TAG, "startPostion=" + dragPostion + ";endPosition=" + dropPostion);

if (dragPostion < dropPostion) {

channelList.add(dropPostion + 1, dragItem);

channelList.remove(dragPostion);

} else {

channelList.add(dropPostion, dragItem);

channelList.remove(dragPostion + 1);

}

isChanged = true;

isListChanged = true;

notifyDataSetChanged();

}

/** 获取频道列表 */

public List<ChannelItem> getChannnelLst() {

return channelList;

}

/** 设置删除的position */

public void setRemove(int position) {

remove_position = position;

notifyDataSetChanged();

}

/** 删除频道列表 */

public void remove() {

channelList.remove(remove_position);

remove_position = -1;

isListChanged = true;

notifyDataSetChanged();

}

/** 设置频道列表 */

public void setListDate(List<ChannelItem> list) {

channelList = list;

}

/** 获取是否可见 */

public boolean isVisible() {

return isVisible;

}

/** 排序是否发生改变 */

public boolean isListChanged() {

return isListChanged;

}

/** 设置是否可见 */

public void setVisible(boolean visible) {

isVisible = visible;

}

/** 显示放下的ITEM */

public void setShowDropItem(boolean show) {

isItemShow = show;

}

}

NewsFragmentPagerAdapter.java

public class NewsFragmentPagerAdapter extends FragmentPagerAdapter {

private ArrayList<Fragment> fragments = new ArrayList<Fragment>();;

private final FragmentManager fm;

public NewsFragmentPagerAdapter(FragmentManager fm) {

super(fm);

this.fm = fm;

}

public NewsFragmentPagerAdapter(FragmentManager fm,

ArrayList<Fragment> fragments) {

super(fm);

this.fm = fm;

this.fragments = fragments;

}

public void appendList(ArrayList<Fragment> fragment) {

fragments.clear();

if (!fragments.containsAll(fragment) && fragment.size() > 0) {

fragments.addAll(fragment);

}

notifyDataSetChanged();

}

@Override

public int getCount() {

return fragments.size();

}

@Override

public Fragment getItem(int position) {

return fragments.get(position);

}

@Override

public int getItemPosition(Object object) {

return POSITION_NONE;

}

public void setFragments(ArrayList<Fragment> fragments) {

if (this.fragments != null) {

FragmentTransaction ft = fm.beginTransaction();

for (Fragment f : this.fragments) {

ft.remove(f);

}

ft.commit();

ft = null;

fm.executePendingTransactions();

}

this.fragments = fragments;

notifyDataSetChanged();

}

@Override

public void destroyItem(ViewGroup container, int position, Object object) {

// 这里Destroy的是Fragment的视图层次,并不是Destroy Fragment对象

super.destroyItem(container, position, object);

}

@Override

public Object instantiateItem(ViewGroup container, int position) {

if (fragments.size() <= position) {

position = position % fragments.size();

}

Object obj = super.instantiateItem(container, position);

return obj;

}

}

OtherAdapter.java

public class OtherAdapter extends BaseAdapter {

private final Context context;

public List<ChannelItem> channelList;

private TextView item_text;

/** 是否可见 */

boolean isVisible = true;

/** 要删除的position */

public int remove_position = -1;

public OtherAdapter(Context context, List<ChannelItem> channelList) {

this.context = context;

this.channelList = channelList;

}

@Override

public int getCount() {

return channelList == null ? 0 : channelList.size();

}

@Override

public ChannelItem getItem(int position) {

if (channelList != null && channelList.size() != 0) {

return channelList.get(position);

}

return null;

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

View view = LayoutInflater.from(context).inflate(R.layout.channel_item, null);

item_text = (TextView) view.findViewById(R.id.text_item);

ChannelItem channel = getItem(position);

item_text.setText(channel.getName());

if (!isVisible && (position == -1 + channelList.size())) {

item_text.setText("");

}

if (remove_position == position) {

item_text.setText("");

}

return view;

}

/** 获取频道列表 */

public List<ChannelItem> getChannnelLst() {

return channelList;

}

/** 添加频道列表 */

public void addItem(ChannelItem channel) {

channelList.add(channel);

notifyDataSetChanged();

}

/** 设置删除的position */

public void setRemove(int position) {

remove_position = position;

notifyDataSetChanged();

// notifyDataSetChanged();

}

/** 删除频道列表 */

public void remove() {

channelList.remove(remove_position);

remove_position = -1;

notifyDataSetChanged();

}

/** 设置频道列表 */

public void setListDate(List<ChannelItem> list) {

channelList = list;

}

/** 获取是否可见 */

public boolean isVisible() {

return isVisible;

}

/** 设置是否可见 */

public void setVisible(boolean visible) {

isVisible = visible;

}

}

(5).实现Bean包下面的类

ChannelItem.java

public class ChannelItem implements Serializable {

/**

*

*/

// private static final long serialVersionUID = -6465237897027410019L;

/**

*/

public Integer id;

/**

*/

public String name;

/**

*/

public Integer orderId;

/**

*/

public Integer selected;

public ChannelItem() {

}

public ChannelItem(int id, String name, int orderId, int selected) {

this.id = Integer.valueOf(id);

this.name = name;

this.orderId = Integer.valueOf(orderId);

this.selected = Integer.valueOf(selected);

}

public int getId() {

return this.id.intValue();

}

public String getName() {

return this.name;

}

public int getOrderId() {

return this.orderId.intValue();

}

public Integer getSelected() {

return this.selected;

}

public void setId(int paramInt) {

this.id = Integer.valueOf(paramInt);

}

public void setName(String paramString) {

this.name = paramString;

}

public void setOrderId(int paramInt) {

this.orderId = Integer.valueOf(paramInt);

}

public void setSelected(Integer paramInteger) {

this.selected = paramInteger;

}

@Override

public String toString() {

return "ChannelItem [id=" + this.id + ", name=" + this.name

+ ", selected=" + this.selected + "]";

}

}

ChannelManage.java

public class ChannelManage {

public static ChannelManage channelManage;

/**

* 默认的用户选择频道列表

*/

public static List<ChannelItem> defaultUserChannels;

/**

* 默认的其他频道列表

*/

public static List<ChannelItem> defaultOtherChannels;

private ChannelDao channelDao;

/** 判断数据库中是否存在用户数据 */

private boolean userExist = false;

static {

defaultUserChannels = new ArrayList<ChannelItem>();

defaultOtherChannels = new ArrayList<ChannelItem>();

defaultUserChannels.add(new ChannelItem(1, "头条", 1, 1));

defaultUserChannels.add(new ChannelItem(2, "足球", 2, 1));

defaultUserChannels.add(new ChannelItem(3, "娱乐", 3, 1));

defaultUserChannels.add(new ChannelItem(4, "体育", 4, 1));

defaultUserChannels.add(new ChannelItem(5, "财经", 5, 1));

defaultUserChannels.add(new ChannelItem(6, "科技", 6, 1));

// defaultUserChannels.add(new ChannelItem(7, "图片", 1, 0));

defaultOtherChannels.add(new ChannelItem(7, "CBA", 1, 0));

defaultOtherChannels.add(new ChannelItem(8, "笑话", 2, 0));

defaultOtherChannels.add(new ChannelItem(9, "汽车", 3, 0));

defaultOtherChannels.add(new ChannelItem(10, "时尚", 4, 0));

defaultOtherChannels.add(new ChannelItem(11, "北京", 5, 0));

defaultOtherChannels.add(new ChannelItem(12, "军事", 6, 0));

defaultOtherChannels.add(new ChannelItem(13, "房产", 7, 0));

defaultOtherChannels.add(new ChannelItem(14, "游戏", 8, 0));

defaultOtherChannels.add(new ChannelItem(15, "精选", 9, 0));

defaultOtherChannels.add(new ChannelItem(16, "电台", 10, 0));

defaultOtherChannels.add(new ChannelItem(17, "情感", 11, 0));

defaultUserChannels.add(new ChannelItem(18, "电影", 12, 0));

defaultUserChannels.add(new ChannelItem(19, "NBA", 13, 0));

defaultUserChannels.add(new ChannelItem(20, "数码", 14, 0));

defaultUserChannels.add(new ChannelItem(21, "移动", 15, 0));

defaultUserChannels.add(new ChannelItem(22, "彩票", 16, 0));

defaultUserChannels.add(new ChannelItem(23, "教育", 17, 0));

defaultUserChannels.add(new ChannelItem(24, "论坛", 18, 0));

defaultOtherChannels.add(new ChannelItem(25, "旅游", 19, 0));

defaultOtherChannels.add(new ChannelItem(26, "手机", 20, 0));

defaultOtherChannels.add(new ChannelItem(27, "博客", 21, 0));

defaultOtherChannels.add(new ChannelItem(28, "社会", 22, 0));

defaultOtherChannels.add(new ChannelItem(29, "家居", 23, 0));

defaultOtherChannels.add(new ChannelItem(30, "暴雪", 24, 0));

defaultUserChannels.add(new ChannelItem(31, "亲子", 25, 0));

}

private ChannelManage(SQLHelper paramDBHelper) throws SQLException {

if (channelDao == null)

channelDao = new ChannelDao(paramDBHelper.getContext());

// NavigateItemDao(paramDBHelper.getDao(NavigateItem.class));

initDefaultChannel();

return;

}

/**

* 初始化频道管理类

*

* @param paramDBHelper

* @throws SQLException

*/

public static ChannelManage getManage(SQLHelper dbHelper) throws SQLException {

if (channelManage == null)

synchronized (ChannelManage.class) {

if (channelManage == null) {

channelManage = new ChannelManage(dbHelper);

}

}

return channelManage;

}

/**

* 清除所有的频道

*/

public void deleteAllChannel() {

channelDao.clearFeedTable();

}

/**

* 获取其他的频道

*

* @return 数据库存在用户配置 ? 数据库内的用户选择频道 : 默认用户选择频道 ;

*/

public List<ChannelItem> getUserChannel() {

Object cacheList = channelDao.listCache(SQLHelper.SELECTED + "= ?", new String[] {

"1"

});

if (cacheList != null && !((List<?>) cacheList).isEmpty()) {

userExist = true;

List<Map<String, String>> maplist = (List) cacheList;

int count = maplist.size();

List<ChannelItem> list = new ArrayList<ChannelItem>();

for (int i = 0; i < count; i++) {

ChannelItem navigate = new ChannelItem();

navigate.setId(Integer.valueOf(maplist.get(i).get(SQLHelper.ID)));

navigate.setName(maplist.get(i).get(SQLHelper.NAME));

navigate.setOrderId(Integer.valueOf(maplist.get(i).get(SQLHelper.ORDERID)));

navigate.setSelected(Integer.valueOf(maplist.get(i).get(SQLHelper.SELECTED)));

list.add(navigate);

}

return list;

}

return defaultUserChannels;

}

/**

* 获取其他的频道

*

* @return 数据库存在用户配置 ? 数据库内的其它频道 : 默认其它频道 ;

*/

public List<ChannelItem> getOtherChannel() {

Object cacheList = channelDao.listCache(SQLHelper.SELECTED + "= ?", new String[] {

"0"

});

List<ChannelItem> list = new ArrayList<ChannelItem>();

if (cacheList != null && !((List) cacheList).isEmpty()) {

List<Map<String, String>> maplist = (List) cacheList;

int count = maplist.size();

for (int i = 0; i < count; i++) {

ChannelItem navigate = new ChannelItem();

navigate.setId(Integer.valueOf(maplist.get(i).get(SQLHelper.ID)));

navigate.setName(maplist.get(i).get(SQLHelper.NAME));

navigate.setOrderId(Integer.valueOf(maplist.get(i).get(SQLHelper.ORDERID)));

navigate.setSelected(Integer.valueOf(maplist.get(i).get(SQLHelper.SELECTED)));

list.add(navigate);

}

return list;

}

if (userExist) {

return list;

}

cacheList = defaultOtherChannels;

return (List<ChannelItem>) cacheList;

}

/**

* 保存用户频道到数据库

*

* @param userList

*/

public void saveUserChannel(List<ChannelItem> userList) {

for (int i = 0; i < userList.size(); i++) {

ChannelItem channelItem = userList.get(i);

channelItem.setOrderId(i);

channelItem.setSelected(Integer.valueOf(1));

channelDao.addCache(channelItem);

}

}

public void updateChannel(ChannelItem channelItem, String selected) {

ContentValues values = new ContentValues();

values.put("selected", selected);

values.put("id", channelItem.getId());

values.put("name", channelItem.getName());

values.put("orderId", channelItem.getOrderId());

channelDao.updateCache(values, " name = ?", new String[] {

channelItem.getName()

});

}

// /**

// * 保存单个用户频道到数据库

// *

// * @param userList

// */

//

// public void saveUserChannel(ChannelItem channelItem) {

// channelDao.addCache(channelItem);

// }

//

// public void deleteUserChannel(ChannelItem channelItem) {

// channelDao.deleteCache(" name=?", new String[] {

// channelItem.getName()

// });

// }

//

// /**

// * 保存单个其他频道到数据库

// *

// * @param userList

// */

// public void saveOtherChannel(ChannelItem channelItem) {

// channelDao.addCache(channelItem);

// }

//

// public void deleteOtherChannel(ChannelItem channelItem) {

// channelDao.deleteCache(" name=?", new String[] {

// channelItem.getName()

// });

// }

/**

* 保存其他频道到数据库

*

* @param otherList

*/

public void saveOtherChannel(List<ChannelItem> otherList) {

for (int i = 0; i < otherList.size(); i++) {

ChannelItem channelItem = otherList.get(i);

channelItem.setOrderId(i);

channelItem.setSelected(Integer.valueOf(0));

channelDao.addCache(channelItem);

}

}

/**

* 初始化数据库内的频道数据

*/

private void initDefaultChannel() {

Log.d("deleteAll", "deleteAll");

deleteAllChannel();

saveUserChannel(defaultUserChannels);

saveOtherChannel(defaultOtherChannels);

}

}

(6).实现Dao包下面的类

ChannelDaoInface.java

public interface ChannelDaoInface {

public boolean addCache(ChannelItem item);

public boolean deleteCache(String whereClause, String[] whereArgs);

public boolean updateCache(ContentValues values, String whereClause,

String[] whereArgs);

public Map<String, String> viewCache(String selection,

String[] selectionArgs);

public List<Map<String, String>> listCache(String selection,

String[] selectionArgs);

public void clearFeedTable();

}

ChannelDao.java

public class ChannelDao implements ChannelDaoInface {

private SQLHelper helper = null;

public ChannelDao(Context context) {

helper = new SQLHelper(context);

}

@Override

public boolean addCache(ChannelItem item) {

boolean flag = false;

SQLiteDatabase database = null;

long id = -1;

try {

database = helper.getWritableDatabase();

database.beginTransaction();

ContentValues values = new ContentValues();

Class<? extends ChannelItem> clazz = item.getClass();

String tableNmae = clazz.getSimpleName();

Method[] methods = clazz.getMethods();

for (Method method : methods) {

String mName = method.getName();

if (mName.startsWith("get") && !mName.startsWith("getClass")) {

String fieldName = mName.substring(3, mName.length()).toLowerCase();

Object value = method.invoke(item, new Object[]{});

if (value instanceof String) {

values.put(fieldName, (String) value);

}

}

}

id = database.insert(tableNmae, null, values);

flag = (id != -1 ? true : false);

database.setTransactionSuccessful();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (database != null) {

database.endTransaction();

database.close();

}

}

return flag;

}

@Override

public boolean deleteCache(String whereClause, String[] whereArgs) {

boolean flag = false;

SQLiteDatabase database = null;

int count = 0;

try {

database = helper.getWritableDatabase();

database.beginTransaction();

count = database.delete(SQLHelper.TABLE_CHANNEL, whereClause, whereArgs);

flag = (count > 0 ? true : false);

database.setTransactionSuccessful();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (database != null) {

database.endTransaction();

database.close();

}

}

return flag;

}

@Override

public boolean updateCache(ContentValues values, String whereClause,

String[] whereArgs) {

boolean flag = false;

SQLiteDatabase database = null;

int count = 0;

try {

database = helper.getWritableDatabase();

database.execSQL("update " + SQLHelper.TABLE_CHANNEL + " set selected = "

+ values.getAsString("selected") + " where id = " + values.getAsString("id"));

flag = (count > 0 ? true : false);

} catch (Exception e) {

e.printStackTrace();

} finally {

if (database != null) {

database.endTransaction();

database.close();

}

}

return flag;

}

@Override

public Map<String, String> viewCache(String selection,

String[] selectionArgs) {

SQLiteDatabase database = null;

Cursor cursor = null;

Map<String, String> map = new HashMap<String, String>();

try {

database = helper.getReadableDatabase();

database.beginTransaction();

cursor = database.query(true, SQLHelper.TABLE_CHANNEL, null, selection,

selectionArgs, null, null, null, null);

int cols_len = cursor.getColumnCount();

while (cursor.moveToNext()) {

for (int i = 0; i < cols_len; i++) {

String cols_name = cursor.getColumnName(i);

String cols_values = cursor.getString(cursor

.getColumnIndex(cols_name));

if (cols_values == null) {

cols_values = "";

}

map.put(cols_name, cols_values);

}

}

database.setTransactionSuccessful();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (database != null) {

database.endTransaction();

cursor.close();

database.close();

}

}

return map;

}

@Override

public List<Map<String, String>> listCache(String selection, String[] selectionArgs) {

List<Map<String, String>> list = new ArrayList<Map<String, String>>();

SQLiteDatabase database = null;

Cursor cursor = null;

try {

database = helper.getReadableDatabase();

database.beginTransaction();

cursor = database.query(false, SQLHelper.TABLE_CHANNEL, null, selection, selectionArgs,

null, null, null, null);

int cols_len = cursor.getColumnCount();

while (cursor.moveToNext()) {

Map<String, String> map = new HashMap<String, String>();

for (int i = 0; i < cols_len; i++) {

String cols_name = cursor.getColumnName(i);

String cols_values = cursor.getString(cursor

.getColumnIndex(cols_name));

if (cols_values == null) {

cols_values = "";

}

map.put(cols_name, cols_values);

}

list.add(map);

}

database.setTransactionSuccessful();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (database != null) {

database.endTransaction();

cursor.close();

database.close();

}

}

return list;

}

@Override

public void clearFeedTable() {

String sql = "DELETE FROM " + SQLHelper.TABLE_CHANNEL + ";";

SQLiteDatabase db = helper.getWritableDatabase();

db.execSQL(sql);

revertSeq();

}

private void revertSeq() {

String sql = "update sqlite_sequence set seq=0 where name='"

+ SQLHelper.TABLE_CHANNEL + "'";

SQLiteDatabase db = helper.getWritableDatabase();

db.execSQL(sql);

}

}

(7).实现Db包下面的类

SQLHelper.java

public class SQLHelper extends SQLiteOpenHelper {

public static final String DB_NAME = "database.db";// 数据库名称

public static final int VERSION = 1;

public static final String TABLE_CHANNEL = "ChannelItem";// 数据表

public static final String ID = "id";//

public static final String NAME = "name";

public static final String ORDERID = "orderId";

public static final String SELECTED = "selected";

private final Context context;

public SQLHelper(Context context) {

super(context, DB_NAME, null, VERSION);

this.context = context;

}

public Context getContext() {

return context;

}

@Override

public void onCreate(SQLiteDatabase db) {

// TODO 创建数据库后,对数据库的操作

String sql = "create table if not exists " + TABLE_CHANNEL +

"(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +

ID + " INTEGER , " +

NAME + " TEXT , " +

ORDERID + " INTEGER , " +

SELECTED + " TEXT)";

db.execSQL(sql);

}

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// TODO 更改数据库版本的操作

onCreate(db);

}

}

(8).实现Fragment包下面的类

DemoFragment.java

public class DemoFragment extends Fragment {

@Nullable

@Override

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

View view =inflater.inflate(R.layout.testdemo,null);

return view;

}

}

(9).实现Utils包下面的类

BaseTools.java

public class BaseTools {

public final static int getWindowsWidth(Activity activity) {

DisplayMetrics dm = new DisplayMetrics();

activity.getWindowManager().getDefaultDisplay().getMetrics(dm);

return dm.widthPixels;

}

}

DataTools.java

public class DataTools {

/**

* dipתΪ px

*/

public static int dip2px(Context context, float dipValue) {

final float scale = context.getResources().getDisplayMetrics().density;

return (int) (dipValue * scale + 0.5f);

}

/**

* px תΪ dip

*/

public static int px2dip(Context context, float pxValue) {

final float scale = context.getResources().getDisplayMetrics().density;

return (int) (pxValue / scale + 0.5f);

}

}

(9).实现View包下面的类

ColumnHorizontalScrollView.java

public class ColumnHorizontalScrollView extends HorizontalScrollView {

/** 传入整体布局 */

private View ll_content;

/** 传入更多栏目选择布局 */

private View ll_more;

/** 传入拖动栏布局 */

private View rl_column;

/** 左阴影图片 */

private ImageView leftImage;

/** 右阴影图片 */

private ImageView rightImage;

/** 屏幕宽度 */

private int mScreenWitdh = 0;

/** 父类的活动activity */

private Activity activity;

public ColumnHorizontalScrollView(Context context) {

super(context);

}

public ColumnHorizontalScrollView(Context context, AttributeSet attrs) {

super(context, attrs);

}

public ColumnHorizontalScrollView(Context context, AttributeSet attrs,

int defStyle) {

super(context, attrs, defStyle);

}

/**

* 在拖动的时候执行

*/

@Override

protected void onScrollChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {

super.onScrollChanged(paramInt1, paramInt2, paramInt3, paramInt4);

shade_ShowOrHide();

if (!activity.isFinishing() && ll_content != null && leftImage != null

&& rightImage != null && ll_more != null && rl_column != null) {

if (ll_content.getWidth() <= mScreenWitdh) {

leftImage.setVisibility(View.GONE);

rightImage.setVisibility(View.GONE);

}

} else {

return;

}

if (paramInt1 == 0) {

leftImage.setVisibility(View.GONE);

rightImage.setVisibility(View.VISIBLE);

return;

}

if (ll_content.getWidth() - paramInt1 + ll_more.getWidth() + rl_column.getLeft() == mScreenWitdh) {

leftImage.setVisibility(View.VISIBLE);

rightImage.setVisibility(View.GONE);

return;

}

leftImage.setVisibility(View.VISIBLE);

rightImage.setVisibility(View.VISIBLE);

}

/**

* 传入父类布局中的资源文件

*/

public void setParam(Activity activity, int mScreenWitdh, View paramView1,

ImageView paramView2, ImageView paramView3, View paramView4, View paramView5) {

this.activity = activity;

this.mScreenWitdh = mScreenWitdh;

ll_content = paramView1;

leftImage = paramView2;

rightImage = paramView3;

ll_more = paramView4;

rl_column = paramView5;

}

/**

* 判断左右阴影的显示隐藏效果

*/

public void shade_ShowOrHide() {

if (!activity.isFinishing() && ll_content != null) {

measure(0, 0);

// 如果整体宽度小于屏幕宽度的话,那左右阴影都隐藏

if (mScreenWitdh >= getMeasuredWidth()) {

leftImage.setVisibility(View.GONE);

rightImage.setVisibility(View.GONE);

}

} else {

return;

}

// 如果滑动在最左边时候,左边阴影隐藏,右边显示

if (getLeft() == 0) {

leftImage.setVisibility(View.GONE);

rightImage.setVisibility(View.VISIBLE);

return;

}

// 如果滑动在最右边时候,左边阴影显示,右边隐藏

if (getRight() == getMeasuredWidth() - mScreenWitdh) {

leftImage.setVisibility(View.VISIBLE);

rightImage.setVisibility(View.GONE);

return;

}

// 否则,说明在中间位置,左、右阴影都显示

leftImage.setVisibility(View.VISIBLE);

rightImage.setVisibility(View.VISIBLE);

}

}

DragGrid.java

public class DragGrid extends GridView {

/** 点击时候的X位置 */

public int downX;

/** 点击时候的Y位置 */

public int downY;

/** 点击时候对应整个界面的X位置 */

public int windowX;

/** 点击时候对应整个界面的Y位置 */

public int windowY;

/** 屏幕上的X */

private int win_view_x;

/** 屏幕上的Y */

private int win_view_y;

/** 拖动的里x的距离 */

int dragOffsetX;

/** 拖动的里Y的距离 */

int dragOffsetY;

/** 长按时候对应postion */

public int dragPosition;

/** Up后对应的ITEM的Position */

private int dropPosition;

/** 开始拖动的ITEM的Position */

private int startPosition;

/** item高 */

private int itemHeight;

/** item宽 */

private int itemWidth;

/** 拖动的时候对应ITEM的VIEW */

private View dragImageView = null;

/** 长按的时候ITEM的VIEW */

private ViewGroup dragItemView = null;

/** WindowManager管理器 */

private WindowManager windowManager = null;

/** */

private WindowManager.LayoutParams windowParams = null;

/** item总量 */

private int itemTotalCount;

/** 一行的ITEM数量 */

private final int nColumns = 4;

/** 行数 */

private int nRows;

/** 剩余部分 */

private int Remainder;

/** 是否在移动 */

private boolean isMoving = false;

/** */

private int holdPosition;

/** 拖动的时候放大的倍数 */

private final double dragScale = 1.2D;

/** 震动器 */

private Vibrator mVibrator;

/** 每个ITEM之间的水平间距 */

private int mHorizontalSpacing = 15;

/** 每个ITEM之间的竖直间距 */

private final int mVerticalSpacing = 15;

/* 移动时候最后个动画的ID */

private String LastAnimationID;

public DragGrid(Context context) {

super(context);

init(context);

}

public DragGrid(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

init(context);

}

public DragGrid(Context context, AttributeSet attrs) {

super(context, attrs);

init(context);

}

public void init(Context context) {

mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

// 将布局文件中设置的间距dip转为px

mHorizontalSpacing = DataTools.dip2px(context, mHorizontalSpacing);

}

@Override

public boolean onInterceptTouchEvent(MotionEvent ev) {

if (ev.getAction() == MotionEvent.ACTION_DOWN) {

downX = (int) ev.getX();

downY = (int) ev.getY();

windowX = (int) ev.getX();

windowY = (int) ev.getY();

setOnItemClickListener(ev);

}

return super.onInterceptTouchEvent(ev);

}

@Override

public boolean onTouchEvent(MotionEvent ev) {

boolean bool = true;

if (dragImageView != null && dragPosition != AdapterView.INVALID_POSITION) {

// 移动时候的对应x,y位置

bool = super.onTouchEvent(ev);

int x = (int) ev.getX();

int y = (int) ev.getY();

switch (ev.getAction()) {

case MotionEvent.ACTION_DOWN:

downX = (int) ev.getX();

windowX = (int) ev.getX();

downY = (int) ev.getY();

windowY = (int) ev.getY();

break;

case MotionEvent.ACTION_MOVE:

onDrag(x, y, (int) ev.getRawX(), (int) ev.getRawY());

if (!isMoving) {

OnMove(x, y);

}

if (pointToPosition(x, y) != AdapterView.INVALID_POSITION) {

break;

}

break;

case MotionEvent.ACTION_UP:

stopDrag();

onDrop(x, y);

requestDisallowInterceptTouchEvent(false);

break;

default:

break;

}

}

return super.onTouchEvent(ev);

}

/** 在拖动的情况 */

private void onDrag(int x, int y, int rawx, int rawy) {

if (dragImageView != null) {

windowParams.alpha = 0.6f;

// windowParams.x = x - win_view_x + viewX;

// windowParams.y = y + win_view_y + viewY;

// windowParams.x = rawx - itemWidth / 2;

// windowParams.y = rawy - itemHeight / 2;

windowParams.x = rawx - win_view_x;

windowParams.y = rawy - win_view_y;

windowManager.updateViewLayout(dragImageView, windowParams);

}

}

/** 在松手下放的情况 */

private void onDrop(int x, int y) {

// 根据拖动到的x,y坐标获取拖动位置下方的ITEM对应的POSTION

int tempPostion = pointToPosition(x, y);

// if (tempPostion != AdapterView.INVALID_POSITION) {

dropPosition = tempPostion;

DragAdapter mDragAdapter = (DragAdapter) getAdapter();

// 显示刚拖动的ITEM

mDragAdapter.setShowDropItem(true);

// 刷新适配器,让对应的ITEM显示

mDragAdapter.notifyDataSetChanged();

// }

}

/**

* 长按点击监听

*

* @param ev

*/

public void setOnItemClickListener(final MotionEvent ev) {

setOnItemLongClickListener(new OnItemLongClickListener() {

@Override

public boolean onItemLongClick(AdapterView<?> parent, View view,

int position, long id) {

int x = (int) ev.getX();// 长安事件的X位置

int y = (int) ev.getY();// 长安事件的y位置

startPosition = position;// 第一次点击的postion

dragPosition = position;

if (startPosition <= 1) {

return false;

}

ViewGroup dragViewGroup = (ViewGroup) getChildAt(dragPosition

- getFirstVisiblePosition());

TextView dragTextView = (TextView) dragViewGroup.findViewById(R.id.text_item);

dragTextView.setSelected(true);

dragTextView.setEnabled(false);

itemHeight = dragViewGroup.getHeight();

itemWidth = dragViewGroup.getWidth();

itemTotalCount = DragGrid.this.getCount();

int row = itemTotalCount / nColumns;// 算出行数

Remainder = (itemTotalCount % nColumns);// 算出最后一行多余的数量

if (Remainder != 0) {

nRows = row + 1;

} else {

nRows = row;

}

// 如果特殊的这个不等于拖动的那个,并且不等于-1

if (dragPosition != AdapterView.INVALID_POSITION) {

// 释放的资源使用的绘图缓存。如果你调用buildDrawingCache()手动没有调用setDrawingCacheEnabled(真正的),你应该清理缓存使用这种方法。

win_view_x = windowX - dragViewGroup.getLeft();// VIEW相对自己的X,半斤

win_view_y = windowY - dragViewGroup.getTop();// VIEW相对自己的y,半斤

dragOffsetX = (int) (ev.getRawX() - x);// 手指在屏幕的上X位置-手指在控件中的位置就是距离最左边的距离

dragOffsetY = (int) (ev.getRawY() - y);// 手指在屏幕的上y位置-手指在控件中的位置就是距离最上边的距离

dragItemView = dragViewGroup;

dragViewGroup.destroyDrawingCache();

dragViewGroup.setDrawingCacheEnabled(true);

Bitmap dragBitmap = Bitmap.createBitmap(dragViewGroup.getDrawingCache());

mVibrator.vibrate(50);// 设置震动时间

startDrag(dragBitmap, (int) ev.getRawX(), (int) ev.getRawY());

hideDropItem();

dragViewGroup.setVisibility(View.INVISIBLE);

isMoving = false;

requestDisallowInterceptTouchEvent(true);

return true;

}

return false;

}

});

}

public void startDrag(Bitmap dragBitmap, int x, int y) {

stopDrag();

windowParams = new WindowManager.LayoutParams();// 获取WINDOW界面的

// Gravity.TOP|Gravity.LEFT;这个必须加

windowParams.gravity = Gravity.TOP | Gravity.LEFT;

// 计算当前项Left离窗体的距离

// windowParams.x = x - (int)((itemWidth / 2) * dragScale);

// windowParams.y = y - (int) ((itemHeight / 2) * dragScale);

// 得到preview左上角相对于屏幕的坐标

windowParams.x = x - win_view_x;

windowParams.y = y - win_view_y;

// this.windowParams.x = (x - this.win_view_x + this.viewX);//位置的x值

// this.windowParams.y = (y - this.win_view_y + this.viewY);//位置的y值

// 设置拖拽item的宽和高

windowParams.width = (int) (dragScale * dragBitmap.getWidth());// 放大dragScale倍,可以设置拖动后的倍数

windowParams.height = (int) (dragScale * dragBitmap.getHeight());// 放大dragScale倍,可以设置拖动后的倍数

this.windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE

| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE

| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON

| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;

this.windowParams.format = PixelFormat.TRANSLUCENT;

this.windowParams.windowAnimations = 0;

ImageView iv = new ImageView(getContext());

iv.setImageBitmap(dragBitmap);

windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);// "window"

windowManager.addView(iv, windowParams);

dragImageView = iv;

}

/** 停止拖动 ,释放并初始化 */

private void stopDrag() {

if (dragImageView != null) {

windowManager.removeView(dragImageView);

dragImageView = null;

}

}

/** 在ScrollView内,所以要进行计算高度 */

@Override

public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);

super.onMeasure(widthMeasureSpec, expandSpec);

}

/** 隐藏 放下 的ITEM */

private void hideDropItem() {

((DragAdapter) getAdapter()).setShowDropItem(false);

}

/** 获取移动动画 */

public Animation getMoveAnimation(float toXValue, float toYValue) {

TranslateAnimation mTranslateAnimation = new TranslateAnimation(

Animation.RELATIVE_TO_SELF, 0.0F,

Animation.RELATIVE_TO_SELF, toXValue,

Animation.RELATIVE_TO_SELF, 0.0F,

Animation.RELATIVE_TO_SELF, toYValue);// 当前位置移动到指定位置

mTranslateAnimation.setFillAfter(true);// 设置一个动画效果执行完毕后,View对象保留在终止的位置。

mTranslateAnimation.setDuration(300L);

return mTranslateAnimation;

}

/** 移动的时候触发 */

public void OnMove(int x, int y) {

// 拖动的VIEW下方的POSTION

int dPosition = pointToPosition(x, y);

// 判断下方的POSTION是否是最开始2个不能拖动的

if (dPosition > 1) {

if ((dPosition == -1) || (dPosition == dragPosition)) {

return;

}

dropPosition = dPosition;

if (dragPosition != startPosition) {

dragPosition = startPosition;

}

int movecount;

// 拖动的=开始拖的,并且 拖动的 不等于放下的

if ((dragPosition == startPosition) || (dragPosition != dropPosition)) {

// 移需要移动的动ITEM数量

movecount = dropPosition - dragPosition;

} else {

// 移需要移动的动ITEM数量为0

movecount = 0;

}

if (movecount == 0) {

return;

}

int movecount_abs = Math.abs(movecount);

if (dPosition != dragPosition) {

// dragGroup设置为不可见

ViewGroup dragGroup = (ViewGroup) getChildAt(dragPosition);

dragGroup.setVisibility(View.INVISIBLE);

float to_x = 1;// 当前下方positon

float to_y;// 当前下方右边positon

// x_vlaue移动的距离百分比(相对于自己长度的百分比)

float x_vlaue = ((float) mHorizontalSpacing / (float) itemWidth) + 1.0f;

// y_vlaue移动的距离百分比(相对于自己宽度的百分比)

float y_vlaue = ((float) mVerticalSpacing / (float) itemHeight) + 1.0f;

Log.d("x_vlaue", "x_vlaue = " + x_vlaue);

for (int i = 0; i < movecount_abs; i++) {

to_x = x_vlaue;

to_y = y_vlaue;

// 像左

if (movecount > 0) {

// 判断是不是同一行的

holdPosition = dragPosition + i + 1;

if (dragPosition / nColumns == holdPosition / nColumns) {

to_x = -x_vlaue;

to_y = 0;

} else if (holdPosition % 4 == 0) {

to_x = 3 * x_vlaue;

to_y = -y_vlaue;

} else {

to_x = -x_vlaue;

to_y = 0;

}

} else {

// 向右,下移到上,右移到左

holdPosition = dragPosition - i - 1;

if (dragPosition / nColumns == holdPosition / nColumns) {

to_x = x_vlaue;

to_y = 0;

} else if ((holdPosition + 1) % 4 == 0) {

to_x = -3 * x_vlaue;

to_y = y_vlaue;

} else {

to_x = x_vlaue;

to_y = 0;

}

}

ViewGroup moveViewGroup = (ViewGroup) getChildAt(holdPosition);

Animation moveAnimation = getMoveAnimation(to_x, to_y);

moveViewGroup.startAnimation(moveAnimation);

// 如果是最后一个移动的,那么设置他的最后个动画ID为LastAnimationID

if (holdPosition == dropPosition) {

LastAnimationID = moveAnimation.toString();

}

moveAnimation.setAnimationListener(new AnimationListener() {

@Override

public void onAnimationStart(Animation animation) {

isMoving = true;

}

@Override

public void onAnimationRepeat(Animation animation) {

}

@Override

public void onAnimationEnd(Animation animation) {

// 如果为最后个动画结束,那执行下面的方法

if (animation.toString().equalsIgnoreCase(LastAnimationID)) {

DragAdapter mDragAdapter = (DragAdapter) getAdapter();

mDragAdapter.exchange(startPosition, dropPosition);

startPosition = dropPosition;

dragPosition = dropPosition;

isMoving = false;

}

}

});

}

}

}

}

}

OtherGridView.java

public class OtherGridView extends GridView {

public OtherGridView(Context paramContext, AttributeSet paramAttributeSet) {

super(paramContext, paramAttributeSet);

}

@Override

public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,

MeasureSpec.AT_MOST);

super.onMeasure(widthMeasureSpec, expandSpec);

}

}

(10).实现color包下面的资源文件

subscribe_item_text_color.xml

<?xml version="1.0" encoding="utf-8"?>

<selector

xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_selected="true" android:color="@color/subscribe_item_selected_stroke" />

<item android:state_pressed="true" android:color="@color/subscribe_item_text_color_pressed" />

<item android:color="@color/subscribe_item_text_color_normal" />

</selector>

top_category_scroll_text_color_day.xml

<?xml version="1.0" encoding="utf-8"?>

<selector

xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_selected="true" android:color="#ffffffff" />

<item android:color="#ff909090" />

</selector>

(11).实现drawable包下面的资源文件

btn_back_selected.xml

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

channel_glide_day_bg.xml

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

radio_buttong_bg.xml

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

subscribe_item_bg.xml

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

(12).实现layout包下面的资源文件

activity_main.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:background="@color/activity_bg_color"

android:orientation="vertical" >

<LinearLayout

android:layout_width="match_parent"

android:layout_height="40.0dip"

android:background="#fff3f3f3"

android:orientation="horizontal" >

<RelativeLayout

android:id="@+id/rl_column"

android:layout_width="0dp"

android:layout_height="40.0dip"

android:layout_weight="1.0" >

<com.yyo.testapp.view.ColumnHorizontalScrollView

android:id="@+id/mColumnHorizontalScrollView"

android:layout_width="match_parent"

android:layout_height="40.0dip"

android:scrollbars="none" >

<LinearLayout

android:id="@+id/mRadioGroup_content"

android:layout_width="fill_parent"

android:layout_height="40.0dip"

android:layout_centerVertical="true"

android:gravity="center_vertical"

android:orientation="horizontal"

android:paddingLeft="10.0dip"

android:paddingRight="10.0dip" />

</com.yyo.testapp.view.ColumnHorizontalScrollView>

<ImageView

android:id="@+id/shade_left"

android:layout_width="10.0dip"

android:layout_height="40.0dip"

android:layout_alignParentLeft="true"

android:layout_centerVertical="true"

android:background="@mipmap/channel_leftblock"

android:visibility="gone" />

<ImageView

android:id="@+id/shade_right"

android:layout_width="10.0dip"

android:layout_height="40.0dip"

android:layout_alignParentRight="true"

android:layout_centerVertical="true"

android:background="@mipmap/channel_rightblock"

android:visibility="visible" />

</RelativeLayout>

<LinearLayout

android:id="@+id/ll_more_columns"

android:layout_width="wrap_content"

android:layout_height="40.0dip" >

<ImageView

android:id="@+id/button_more_columns"

android:layout_width="40.0dip"

android:layout_height="40.0dip"

android:layout_gravity="center_vertical"

android:onClick="onMoreColumns"

android:src="@drawable/channel_glide_day_bg" />

</LinearLayout>

</LinearLayout>

<View

android:id="@+id/category_line"

android:layout_width="fill_parent"

android:layout_height="0.5dip"

android:background="#ffdddddd" />

<RelativeLayout

android:layout_width="match_parent"

android:layout_height="match_parent" >

<android.support.v4.view.ViewPager

android:id="@+id/mViewPager"

android:layout_width="match_parent"

android:layout_height="match_parent" />

<RelativeLayout

android:id="@+id/toast_conten"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true" />

</RelativeLayout>

</LinearLayout>

(13).实现values包下面的资源文件

attrs.xml

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

colors.xml

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

strings.xml

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

styles.xml

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

(14).实现AndroidManifest.xml文件配置

Android开发实现自定义式菜单选项(模仿头条的菜单配置)

展开阅读全文

没有更多推荐了,返回首页