Commit 600d1acd by konghaorui

补充动态模块

parent 4c9868f1
......@@ -203,6 +203,7 @@ dependencies {
implementation project(':m-muse')
implementation project(':m-im')
implementation project(':m-dynamic')
// api rootProject.ext.dependencies["ydl-m-fm-module-ydl"]
......
......@@ -13,12 +13,10 @@ import android.util.Log
import com.alibaba.android.arouter.launcher.ARouter
import com.tbruyelle.rxpermissions2.RxPermissions
import com.umeng.analytics.MobclickAgent
import com.ydl.audioim.YDLavManager
import com.ydl.component.music.FragmentContainerActivity
import com.ydl.component.home.HomeActivity
import com.ydl.component.music.FragmentContainerActivity
import com.ydl.component.mvp.DemoContract
import com.ydl.component.mvp.DemoPresenter
import com.ydl.confide.home.ConfideHomeActivity
import com.ydl.media.audio.PlayService
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
......@@ -98,6 +96,9 @@ class MainActivity : BaseLceActivity<DemoContract.View, DemoContract.Presenter>(
bt_to_im.setOnClickListener {
FragmentContainerActivity.start(this,"NewMultiMessageFragment")
}
bt_to_dynamic.setOnClickListener {
FragmentContainerActivity.start(this,"TrendsHomeFragment")
}
bt_to_tests.setOnClickListener {
startActivity(Intent(this, NewTestHomeActivity::class.java))
}
......
......@@ -7,6 +7,7 @@ import com.ydl.component.mvp.DemoContract
import com.ydl.component.mvp.DemoPresenter
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.mvp.lce.BaseLceActivity
import com.yidianling.dynamic.trendsHome.TrendsHomeFragment
import com.yidianling.im.ui.page.NewMultiMessageFragment
......@@ -59,6 +60,9 @@ class FragmentContainerActivity : BaseLceActivity<DemoContract.View, DemoContra
if ("NewMultiMessageFragment" == fragmentName) {
return NewMultiMessageFragment()
}
if ("TrendsHomeFragment" == fragmentName) {
return TrendsHomeFragment()
}
return PlayFragment()
}
}
......@@ -176,6 +176,14 @@
android:layout_weight="1"
android:layout_marginRight="10dp"
android:text="私聊" />
<Button
android:id="@+id/bt_to_dynamic"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="10dp"
android:text="动态" />
</LinearLayout>
</LinearLayout>
......
......@@ -59,6 +59,7 @@ buildscript {
classpath 'com.ydl.plugins:modular:1.0.3'
classpath 'com.ydl:notracepoint-gradle-plugin:0.0.3'
classpath 'com.ydl.plugins:restools:0.0.1'
classpath 'com.jakewharton:butterknife-gradle-plugin:9.0.0-rc1'
}
}
......
......@@ -31,7 +31,7 @@ ext {
retrofitSdkVersion : "2.6.0",
dagger2SdkVersion : "2.23.2",
glideSdkVersion : "4.3.1",
butterknifeSdkVersion : "8.8.1",
butterknifeSdkVersion : "9.0.0-rc1",
rxlifecycleSdkVersion : "1.0",
rxlifecycle2SdkVersion : "2.2.2",
espressoSdkVersion : "3.0.1",
......
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'resTools' // 资源重命名插件
apply plugin: 'com.jakewharton.butterknife'
// 配置资源重命名插件
resConfig {
new_prefix = 'dynamic_' // 资源前缀
old_prefix = '' // 老前缀,可为''空字符串
}
kapt {
arguments {
arg("AROUTER_MODULE_NAME", "dynamic")
}
}
android {
compileSdkVersion rootProject.ext.android["compileSdkVersion"]
buildToolsVersion rootProject.ext.android["buildToolsVersion"]
defaultConfig {
minSdkVersion rootProject.ext.android["minSdkVersion"]
targetSdkVersion rootProject.ext.android["targetSdkVersion"]
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: "dynamic"]
}
}
flavorDimensions "versionCode"//Flavor 维度信息
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
//前缀的名字
//resourcePrefix "dynamic_"
//Flavor 信息
publishNonDefault true
productFlavors {
ydl {}
xlzx {}
}
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
res.srcDirs = [
'src/main/res'
]
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
exclude 'META-INF/rxjava.properties'
}
}
dependencies {
api fileTree(dir: 'libs', include: ['*.aar','*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
kapt 'com.alibaba:arouter-compiler:1.2.2'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.github.ksoichiro:android-observablescrollview:1.6.0'
implementation 'com.pnikosis:materialish-progress:1.7'
implementation 'com.daimajia.numberprogressbar:library:1.4@aar'
implementation 'me.relex:circleindicator:1.2.2@aar'
implementation 'com.github.faruktoptas:FancyShowCaseView:0.1.1'
kapt rootProject.ext.dependencies["butterknife-compiler"]
api rootProject.ext.dependencies["butterknife"]
api rootProject.ext.dependencies["ydl-user-router"]
if (rootProject.ext.dev_mode){
//开发时使用
api project(':ydl-webview')
api project(':ydl-platform')
api project(":ydl-pay")
implementation modularPublication('com.ydl:m-user-api')
implementation modularPublication('com.ydl:m-audioim-api')
}else {
//发布时使用
api rootProject.ext.dependencies["ydl-pay"]
compileOnly rootProject.ext.dependencies["ydl-m-user-api"]
compileOnly rootProject.ext.dependencies["ydl-m-audioim-api"]
api rootProject.ext.dependencies["ydl-webview"]
api(rootProject.ext.dependencies["ydl-platform"]) {
transitive = true
}
}
}
modular {
//模块包名
packageName "com.yidianling.dynamic"
// 模块发布需要的参数
publish {
modules {
xlzx {
groupId = "com.ydl"
artifactId = "m-dynamic-module-xlzx"
// 上报的 心理咨询 业务模块 aar 包的版本号
version = rootProject.ext.ydlPublishVersion[childProject.getName()]
}
ydl{
groupId = "com.ydl"
artifactId = "m-dynamic-module-ydl"
// 上报的 壹点灵 业务模块 aar 包的版本号
version = rootProject.ext.ydlPublishVersion[childProject.getName()]
}
}
api {
//壹点灵/心理咨询 业务模块 API层 jar包的发布信息
groupId = "com.ydl"
artifactId = "m-dynamic-api"
//开发时注释掉版本号,发布api时打开
//version = rootProject.ext.ydlPublishVersion[childProject.getName()+"-api"]
// API 层打包时需要引入的依赖
apiDependencies {
implementation "com.google.code.gson:gson:2.8.2"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.alibaba:arouter-api:1.4.1'
}
}
}
}
\ No newline at end of file
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
package com.yidianling.dynamic
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.yidianling.dynamic", appContext.packageName)
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yidianling.dynamic">
<uses-permission android:name="android.permission.INTERNET" />
<application>
<activity
android:name=".trendsDetail.TrendsDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name=".topic.topicDetail.TopicDetailActivity"
android:screenOrientation="portrait"
/>
<activity
android:name=".publishTrend.PublishTrendActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activity.TrendsReplyInfoActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activity.MyTrendsActivity"
android:screenOrientation="portrait" />
<activity
android:name=".common.browsePictures.BrowsePicturesActivity"
android:screenOrientation="portrait" />
<activity
android:name=".common.browsePictures.BrowsePicturesActivity2"
android:screenOrientation="portrait" />
<activity
android:name=".members.MembersActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait" />
<activity
android:name=".publishTrend.SelecTopicActivity"
android:screenOrientation="portrait" />
<activity
android:name=".topic.AllTopicActivity"
android:screenOrientation="portrait" />
<activity
android:name=".thank.ThankActivity"
android:screenOrientation="portrait" />
</application>
</manifest>
\ No newline at end of file
package com.yidianling.dynamic
import com.ydl.ydlcommon.base.config.HttpConfig
class DynamicConstants {
companion object {
var ZHUANJIA = HttpConfig.YDL_H5+ "confideDetail?id="
var WWWXIADAN = HttpConfig.H5_URL+ "consult/commit/"
//赞过的动态列表
var TRENDS_ZAN_LIST_H5 = HttpConfig.H5_URL+ "active/active-members"
//感谢一页请求的数据
const val THX_REPLY_PAGE_SIZE = 20
const val EACH_PAGE_DATA_NUM = 20
/**
* 保存图片成功
*/
const val REQUEST_SAVE_IMG_SUCCESS = 21004
/**
* 保存图片失败
*/
const val REQUEST_SAVE_IMG_FAIL = 21005
/**
* 发表动态从图库中获取图片
*/
const val REQUEST_CODE_GALLERY_TREN = 21006
/**
* 发表动态拍照
*/
const val REQUEST_CODE_CAMER_TREND = 21007
/**
* 选择话题
*/
const val REQUEST_CODE_SELECT_TOPIC = 21008
//从话题详情页或用户主页跳转到动态详情
const val JUMP_TREND_INFO = 30006
/**
* 发布动态选取的图片查看大图后删除
*/
const val PUBLISH_PIC_BROW = 21009
const val IMAGE_PICKER = 32001
/**
* 话题详情最新动态列表刷新
*/
const val TOPIC_DETAIL_NEW_REFRESH = 32101
/**
* 话题详情热门动态列表刷新
*/
const val TOPIC_DETAIL_HOT_REFRESH = 32102
/**
* 个人主页动态列表刷新
*/
const val MEMBER_REFRESH = 32103
open var TOPIC_DETAIL_H5 = HttpConfig.H5_URL+ "active/topic-members/"
open var TRENF_INFO_SHARE_H5 = HttpConfig.H5_URL + "ask/"
const val PUBLISH_TYPE = "publish_type"
const val SILENCED_CODE = 1000020
const val BIND_PHONE_ACTION = "wxbind"
const val HELP_URL = "https://h2.yidianling.com/ex-help/96"
val BIND_PHONE = "为了及时接收消息通知,请立即绑定手机"
}
}
package com.yidianling.dynamic;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.ydl.ydlcommon.ui.LoadingDialogFragment;
/**
* Created by xiongyu on 2017/3/13.
*/
public class DynamicFragment extends Fragment {
boolean isonActivityCreated;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isonActivityCreated=true;
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
onPause();
}else{
onResume();
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//相当于Fragment的onResume
if(isonActivityCreated){
onResume();
}
} else {
//相当于Fragment的onPause
if(isonActivityCreated){
onPause();
}
}
}
protected LoadingDialogFragment loadingDialogFragment;
public void showProgressDialog(String msg){
if (loadingDialogFragment == null){
loadingDialogFragment = LoadingDialogFragment.Companion.newInstance(msg);
}
loadingDialogFragment.show(getChildFragmentManager(), null);
}
public void dismissProgressDialog(){
if (loadingDialogFragment != null && loadingDialogFragment.isAdded()){
loadingDialogFragment.dismissAllowingStateLoss();
loadingDialogFragment = null;
}
}
@Override
public void onDetach() {
super.onDetach();
dismissProgressDialog();
}
}
package com.yidianling.dynamic.activity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import butterknife.ButterKnife
import com.ydl.ydlcommon.base.BaseActivity
import com.yidianling.dynamic.R
import com.yidianling.dynamic.router.DynamicIn
import com.yidianling.dynamic.trendList.TrendsListFragment
import kotlinx.android.synthetic.main.activity_mytrends.*
import java.util.*
/**
* 我的动态
* Created by hgw on 2017/3/29.
*/
class MyTrendsActivity : BaseActivity() {
internal var select_tab: Int = 0//当前动态列表的标示
internal var tab = "3"
internal var page = 1
private var sendFragment: TrendsListFragment? = null
private var replyFragment: TrendsListFragment? = null//我发布的和我回复的
private var pagerAdapter: FragmentPagerAdapter? = null
private val fragmentList = ArrayList<TrendsListFragment>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mytrends)
ButterKnife.bind(this)
sendFragment = TrendsListFragment.newInstance(
1,
0,
TrendsListFragment.TREND_TYPE_MY_TREND,
DynamicIn.getUserInfo()!!.uid + ""
)
replyFragment = TrendsListFragment.newInstance(
2,
0,
TrendsListFragment.TREND_TYPE_MY_TREND,
DynamicIn.getUserInfo()!!.uid + ""
)
fragmentList.add(sendFragment!!)
fragmentList.add(replyFragment!!)
initV()
initClick()
}
private fun initV() {
pagerAdapter = object : FragmentPagerAdapter(supportFragmentManager) {
override fun getItem(position: Int): Fragment {
return fragmentList[position]
}
override fun getCount(): Int {
return fragmentList.size
}
}
viewpager_frag!!.adapter = pagerAdapter
viewpager_frag!!.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
changeLabel(position, false)
}
override fun onPageScrollStateChanged(state: Int) {
}
})
}
private fun initClick() {
image_back.setOnClickListener {
finish()
}
item_topic_detail_new_tv.setOnClickListener {
//我发布的
changeLabel(0, true)
}
item_topic_detail_hot_tv.setOnClickListener {
//我评论的
changeLabel(1, true)
}
}
//切换标签选中状态
private fun changeLabel(position: Int, isChangeFragment: Boolean) {
if (position == 0) {
item_topic_detail_new_tv!!.setTextColor(resources.getColor(R.color.title_green))
item_topic_detail_new_hint_tv!!.setBackgroundColor(resources.getColor(R.color.title_green))
item_topic_detail_hot_tv!!.setTextColor(resources.getColor(R.color.text_gray))
item_topic_detail_hot_hint_tv!!.setBackgroundColor(resources.getColor(R.color.white))
} else if (position == 1) {
item_topic_detail_new_tv!!.setTextColor(resources.getColor(R.color.text_gray))
item_topic_detail_new_hint_tv!!.setBackgroundColor(resources.getColor(R.color.white))
item_topic_detail_hot_tv!!.setTextColor(resources.getColor(R.color.title_green))
item_topic_detail_hot_hint_tv!!.setBackgroundColor(resources.getColor(R.color.title_green))
}
if (isChangeFragment) {
viewpager_frag!!.currentItem = position
}
}
override fun layoutResId(): Int {
return 0
}
override fun initDataAndEvent() {
}
}
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ydl.ydl_image.module.GlideApp;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.RecommendTopic;
import com.ydl.ydlcommon.view.widgets.RoundImageView;
import java.util.List;
/**
* Created by xiongyu on 2017/3/14.
*/
public class AllTopicAdapter extends RecyclerView.Adapter<AllTopicViewHolder> {
protected Context mContext;
protected List<RecommendTopic> mDatas;
protected LayoutInflater mInflater;
public interface OnItemClickLister {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
public interface OnFocusClickLister {
void onFocusClick(View view, int position);
void onFocusLongClick(View view, int position);
}
private OnFocusClickLister mOnFocusClickLister;
private OnItemClickLister mOnItemClickLister;
public void setOnItemClickLister(OnItemClickLister lister) {
this.mOnItemClickLister = lister;
}
public void setmOnFocusClickLister(OnFocusClickLister lister) {
this.mOnFocusClickLister = lister;
}
public AllTopicAdapter(List<RecommendTopic> mDatas, Context mContext) {
this.mContext = mContext;
this.mDatas = mDatas;
mInflater = LayoutInflater.from(mContext);
}
@Override
public AllTopicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mInflater.inflate(R.layout.item_alltopic,parent,false);
AllTopicViewHolder viewHolder= new AllTopicViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(AllTopicViewHolder holder, int position) {
RecommendTopic recommendTopic=mDatas.get(position);
String img_url=recommendTopic.getImg_bg_url();
String topic_title=recommendTopic.getTopic_title();
String trend_num=recommendTopic.getTrend_num();
String focus_num=recommendTopic.getFocus_num();
String focus_state=recommendTopic.getFocus_state();
GlideApp.with(mContext)
.load(img_url)
.placeholder(R.drawable.default_img)
.error(R.drawable.default_img)
.into(holder.item_topic_iv);
holder.item_topic_title_tv.setText(topic_title);
holder.item_topic_trend_num_tv.setText(String.format("动态 %s", trend_num));
holder.item_topic_focus_num_tv.setText(String.format("关注 %s", focus_num));
if("1".equals(focus_state)){//1已关注,2未关注
holder.item_topic_trend_focus_rel.setVisibility(View.GONE);
}else if("2".equals(focus_state)){
holder.item_topic_trend_focus_rel.setVisibility(View.VISIBLE);
holder.item_topic_trend_focus_tv.setText("+ 关注");
}
setUpItemEvent(holder);
setUpFocusEvent(holder);
}
@Override
public int getItemCount() {
return mDatas.size();
}
/**
* 添加股据到指定位置
* @param pos 数据添加的位置
* @param recommendtopic 数据
*/
public void addData(int pos,RecommendTopic recommendtopic){
mDatas.add(recommendtopic);
notifyItemInserted(pos);
}
/**
* 删除股票到指定位置
* @param pos
*/
public void deleteData(int pos){
mDatas.remove(pos);
notifyItemRemoved(pos);
}
public void updateDate(List<RecommendTopic> mDatas) {
this.mDatas = mDatas;
notifyDataSetChanged();
}
/**
* 给item添加监听
* @param holder
*/
protected void setUpItemEvent(final AllTopicViewHolder holder){
if(mOnItemClickLister!=null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemClick(holder.itemView,layoutPosition);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemLongClick(holder.itemView,layoutPosition);
return false;
}
});
}
}
/**
* 给关注按钮添加监听
* @param holder
*/
protected void setUpFocusEvent(final AllTopicViewHolder holder){
if(mOnFocusClickLister!=null){
holder.item_topic_trend_focus_rel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnFocusClickLister.onFocusClick(holder.item_topic_trend_focus_rel,layoutPosition);
}
});
holder.item_topic_trend_focus_rel.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnFocusClickLister.onFocusLongClick(holder.item_topic_trend_focus_rel,layoutPosition);
return false;
}
});
}
}
}
class AllTopicViewHolder extends RecyclerView.ViewHolder{
RoundImageView item_topic_iv;
TextView item_topic_title_tv,item_topic_focus_num_tv,item_topic_trend_num_tv,item_topic_trend_focus_tv;
RelativeLayout item_topic_trend_focus_rel;
public AllTopicViewHolder(View itemView) {
super(itemView);
item_topic_iv=(RoundImageView)itemView.findViewById(R.id.item_topic_iv);
item_topic_title_tv=(TextView)itemView.findViewById(R.id.item_topic_title_tv);
item_topic_focus_num_tv=(TextView)itemView.findViewById(R.id.item_topic_focus_num_tv);
item_topic_trend_num_tv=(TextView)itemView.findViewById(R.id.item_topic_trend_num_tv);
item_topic_trend_focus_tv=(TextView)itemView.findViewById(R.id.item_topic_trend_focus_tv);
item_topic_trend_focus_rel=(RelativeLayout)itemView.findViewById(R.id.item_topic_trend_focus_rel);
}
}
\ No newline at end of file
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.yidianling.dynamic.R;
import java.util.List;
/**
* Created by xiongyu on 2017/3/14.
*/
public class DialogListAdapter extends RecyclerView.Adapter<DialogListViewHolder> {
protected Context mContext;
protected List<String> mDatas;
protected LayoutInflater mInflater;
protected int itemTextColor;
public interface OnItemClickLister {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickLister mOnItemClickLister;
public void setOnItemClickLister(OnItemClickLister lister) {
this.mOnItemClickLister = lister;
}
public DialogListAdapter(List<String> mDatas, int itemTextColor,Context mContext) {
this.mContext = mContext;
this.mDatas = mDatas;
this.itemTextColor=itemTextColor;
mInflater = LayoutInflater.from(mContext);
}
@Override
public DialogListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mInflater.inflate(R.layout.item_dialog_list,parent,false);
DialogListViewHolder viewHolder= new DialogListViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(DialogListViewHolder holder, int position) {
String txt=mDatas.get(position);
if((0 != itemTextColor)){
holder.item_dialog_tv.setTextColor(itemTextColor);
}
holder.item_dialog_tv.setText(txt);
setUpItemEvent(holder);
}
@Override
public int getItemCount() {
return mDatas.size();
}
/**
* 添加股据到指定位置
* @param pos 数据添加的位置
* @param obj 数据
*/
public void addData(int pos,String obj){
mDatas.add(obj);
notifyItemInserted(pos);
}
/**
* 删除股票到指定位置
* @param pos
*/
public void deleteData(int pos){
mDatas.remove(pos);
notifyItemRemoved(pos);
}
/**
* 给item添加监听
* @param holder
*/
protected void setUpItemEvent(final DialogListViewHolder holder){
if(mOnItemClickLister!=null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemClick(holder.itemView,layoutPosition);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemLongClick(holder.itemView,layoutPosition);
return false;
}
});
}
}
}
class DialogListViewHolder extends RecyclerView.ViewHolder{
TextView item_dialog_tv;
public DialogListViewHolder(View itemView) {
super(itemView);
item_dialog_tv=(TextView)itemView.findViewById(R.id.item_dialog_tv);
}
}
\ No newline at end of file
package com.yidianling.dynamic.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by xiongyu on 2017/3/27.
*/
public abstract class LazyFragmentPagerAdapter extends LazyPagerAdapter<Fragment> {
private static final String TAG = "LazyFragmentPagerAdapter";
private static final boolean DEBUG = false;
private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;
public LazyFragmentPagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
}
@Override
public void startUpdate(ViewGroup container) {
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
final long itemId = getItemId(position);
// Do we already have this fragment?
String name = makeFragmentName(container.getId(), itemId);
Fragment fragment = mFragmentManager.findFragmentByTag(name);
if (fragment != null) {
if (DEBUG){
}
// Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
mCurTransaction.attach(fragment);
} else {
fragment = getItem(container, position);
if (fragment instanceof Laziable) {
mLazyItems.put(position, fragment);
} else {
mCurTransaction.add(container.getId(), fragment, name);
}
}
if (fragment != getCurrentItem()) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
if (DEBUG){
}
// Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object + " v=" + ((Fragment) object).getView());
final long itemId = getItemId(position);
String name = makeFragmentName(container.getId(), itemId);
if (mFragmentManager.findFragmentByTag(name) == null) {
mCurTransaction.detach((Fragment) object);
} else {
mLazyItems.remove(position);
}
}
@Override
public Fragment addLazyItem(ViewGroup container, int position) {
Fragment fragment = mLazyItems.get(position);
if (fragment == null)
return null;
final long itemId = getItemId(position);
String name = makeFragmentName(container.getId(), itemId);
if (mFragmentManager.findFragmentByTag(name) == null) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
mCurTransaction.add(container.getId(), fragment, name);
mLazyItems.remove(position);
}
return fragment;
}
@Override
public void finishUpdate(ViewGroup container) {
if (mCurTransaction != null) {
mCurTransaction.commitAllowingStateLoss();
mCurTransaction = null;
mFragmentManager.executePendingTransactions();
}
}
@Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView() == view;
}
public long getItemId(int position) {
return position;
}
private static String makeFragmentName(int viewId, long id) {
return "android:switcher:" + viewId + ":" + id;
}
/**
* mark the fragment can be added lazily
*/
public interface Laziable {
}
}
package com.yidianling.dynamic.adapter;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;
/**
* PagerAdapter that items added lazily
* @param <T>
*/
public abstract class LazyPagerAdapter<T> extends PagerAdapter {
protected SparseArray<T> mLazyItems = new SparseArray<T>();
private T mCurrentItem;
/**
* add lazy item to container
* @param container {@link LazyViewPager}
* @param position the position that the item added to
* @return the item added
*/
protected abstract T addLazyItem(ViewGroup container, int position);
/**
* get the lazy item
* @param container {@link LazyViewPager}
* @param position the position of lazy item
* @return the lazy item
*/
protected abstract T getItem(ViewGroup container, int position);
/**
* whether the item is lazily or not
* @param position the position of item
* @return the item is lazily
*/
public boolean isLazyItem(int position) {
return mLazyItems.get(position) != null;
}
/**
* get the current item
* @return the current item
*/
public T getCurrentItem() {
return mCurrentItem;
}
/**
* call {@link LazyPagerAdapter#addLazyItem(ViewGroup, int)}
* to prevent {@link LazyViewPager#onPageScrolled(int, float, int)} not working when the offset of {@link LazyViewPager} is too big
*/
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
mCurrentItem = addLazyItem(container, position);
}
}
\ No newline at end of file
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.yidianling.dynamic.R;
/**
* 懒加载viewPager
* Created by xiongyu on 2017/3/27.
*/
public class LazyViewPager extends ViewPager {
private static final float DEFAULT_OFFSET = 0.5f;
private LazyPagerAdapter mLazyPagerAdapter;
private float mInitLazyItemOffset = DEFAULT_OFFSET;
public LazyViewPager(Context context) {
super(context);
}
public LazyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LazyViewPager);
setInitLazyItemOffset(a.getFloat(R.styleable.LazyViewPager_init_lazy_item_offset, DEFAULT_OFFSET));
a.recycle();
}
/**
* change the initLazyItemOffset
* @param initLazyItemOffset set mInitLazyItemOffset if {@code 0 < initLazyItemOffset <= 1}
*/
public void setInitLazyItemOffset(float initLazyItemOffset) {
if (initLazyItemOffset > 0 && initLazyItemOffset <= 1) {
mInitLazyItemOffset = initLazyItemOffset;
}
}
@Override
public void setAdapter(PagerAdapter adapter) {
super.setAdapter(adapter);
mLazyPagerAdapter = adapter != null && adapter instanceof LazyPagerAdapter ? (LazyPagerAdapter) adapter : null;
}
@Override
protected void onPageScrolled(int position, float offset, int offsetPixels) {
if (mLazyPagerAdapter != null) {
if (getCurrentItem() == position) {
int lazyPosition = position + 1;
if (offset >= mInitLazyItemOffset && mLazyPagerAdapter.isLazyItem(lazyPosition)) {
mLazyPagerAdapter.startUpdate(this);
mLazyPagerAdapter.addLazyItem(this, lazyPosition);
mLazyPagerAdapter.finishUpdate(this);
}
} else if (getCurrentItem() > position) {
int lazyPosition = position;
if (1 - offset >= mInitLazyItemOffset && mLazyPagerAdapter.isLazyItem(lazyPosition)) {
mLazyPagerAdapter.startUpdate(this);
mLazyPagerAdapter.addLazyItem(this, lazyPosition);
mLazyPagerAdapter.finishUpdate(this);
}
}
}
super.onPageScrolled(position, offset, offsetPixels);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int curPosition;
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
curPosition = this.getCurrentItem();
int count = this.getAdapter().getCount();
// Log.i(TAG, "curPosition:=" +curPosition);
// 当当前页面在最后一页和第0页的时候,由父亲拦截触摸事件
if (curPosition == count - 1|| curPosition==0) {
getParent().requestDisallowInterceptTouchEvent(false);
} else {//其他情况,由孩子拦截触摸事件
getParent().requestDisallowInterceptTouchEvent(true);
}
}
return super.dispatchTouchEvent(ev);
}
}
\ No newline at end of file
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydl_image.transform.GlideRoundTransform;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.RecommendTrendImage;
import java.util.List;
/**
* Created by xiongyu on 2017/3/17.
*/
public class PublishTrendImgAdapter extends RecyclerView.Adapter<PublishTrendImgViewHolder> {
private static final String TAG = "RecommendTrendImgAdapte";
protected Context mContext;
protected List<RecommendTrendImage> mDatas;
protected LayoutInflater mInflater;
public interface OnItemClickLister {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
public interface OnDeleteClickLister {
void onDeleteClick(View view, int position);
void onDeleteLongClick(View view, int position);
}
public interface OnAddClickLister {
void OnAddClick(View view, int position);
void OnAddLongClick(View view, int position);
}
private OnItemClickLister mOnItemClickLister;
private OnDeleteClickLister mOnDeleteClickLister;
private OnAddClickLister mOnAddClickLister;
public void setOnItemClickLister(OnItemClickLister lister) {
this.mOnItemClickLister = lister;
}
public void setOnDeleteClickLister(OnDeleteClickLister lister) {
this.mOnDeleteClickLister = lister;
}
public void setOnAddClickLister(OnAddClickLister lister) {
this.mOnAddClickLister = lister;
}
public PublishTrendImgAdapter(List<RecommendTrendImage> mDatas, Context mContext) {
this.mContext = mContext;
this.mDatas = mDatas;
mInflater = LayoutInflater.from(mContext);
}
@Override
public PublishTrendImgViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
view = mInflater.inflate(R.layout.item_publish_trend_img, parent, false);
PublishTrendImgViewHolder viewHolder = new PublishTrendImgViewHolder(view);
return viewHolder;
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onBindViewHolder(PublishTrendImgViewHolder holder, final int position) {
RecommendTrendImage trendImage = mDatas.get(position);
String path = trendImage.getImage_url();
if ("default".equals(path)) {
holder.bg_iv.setVisibility(View.VISIBLE);
holder.item_publish_iv.setVisibility(View.GONE);
holder.item_publish_cancel_iv.setVisibility(View.GONE);
} else {
holder.item_publish_cancel_iv.setVisibility(View.VISIBLE);
holder.bg_iv.setVisibility(View.GONE);
holder.item_publish_iv.setVisibility(View.VISIBLE);
GlideApp.with(mContext)
.load(path)
.error(R.drawable.default_img)
.transform(new GlideRoundTransform(mContext, 6))
// .centerCrop()
.into(holder.item_publish_iv);
}
setUpItemEvent(holder);
setUpDeleteEvent(holder);
setUpAddEvent(holder);
}
@Override
public int getItemCount() {
return mDatas.size();
}
public void updateDate(List<RecommendTrendImage> mDatas) {
this.mDatas = mDatas;
notifyDataSetChanged();
}
/**
* 添加据到指定位置
*
* @param pos 数据添加的位置
* @param trendImage 数据
*/
public void addData(int pos, RecommendTrendImage trendImage) {
mDatas.add(trendImage);
notifyItemInserted(pos);
}
/**
* 删除指定位置数据
*
* @param pos
*/
public void deleteData(int pos) {
mDatas.remove(pos);
notifyItemRemoved(pos);
}
/**
* 给item添加监听
*
* @param holder
*/
protected void setUpItemEvent(final PublishTrendImgViewHolder holder) {
if (mOnItemClickLister != null) {
holder.item_publish_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnItemClickLister.onItemClick(holder.item_publish_iv, layoutPosition);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnItemClickLister.onItemLongClick(holder.item_publish_iv, layoutPosition);
return false;
}
});
}
}
/**
* 添加监听
*
* @param holder
*/
protected void setUpDeleteEvent(final PublishTrendImgViewHolder holder) {
if (mOnItemClickLister != null) {
holder.item_publish_cancel_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnDeleteClickLister.onDeleteClick(holder.item_publish_cancel_iv, layoutPosition);
}
});
holder.item_publish_cancel_iv.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnDeleteClickLister.onDeleteLongClick(holder.item_publish_cancel_iv, layoutPosition);
return false;
}
});
}
}
/**
* 添加监听
*
* @param holder
*/
protected void setUpAddEvent(final PublishTrendImgViewHolder holder) {
if (mOnAddClickLister != null) {
holder.bg_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnAddClickLister.OnAddClick(holder.bg_iv, layoutPosition);
}
});
holder.bg_iv.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnAddClickLister.OnAddLongClick(holder.bg_iv, layoutPosition);
return false;
}
});
}
}
}
class PublishTrendImgViewHolder extends RecyclerView.ViewHolder {
ImageView item_publish_iv, item_publish_cancel_iv, bg_iv;
public PublishTrendImgViewHolder(View itemView) {
super(itemView);
bg_iv = (ImageView) itemView.findViewById(R.id.item_publish_defult_iv);
item_publish_iv = (ImageView) itemView.findViewById(R.id.item_publish_iv);
item_publish_cancel_iv = (ImageView) itemView.findViewById(R.id.item_publish_cancel_iv);
}
}
\ No newline at end of file
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.RecommendedDiscuss;
import com.ydl.ydlcommon.utils.MoonUtil;
import java.util.List;
/**
* Created by xiongyu on 2017/3/14.
*/
public class RecommendDicussAdapter extends RecyclerView.Adapter<RecommendDicussViewHolder> {
protected Context mContext;
protected List<RecommendedDiscuss> mDatas;
protected LayoutInflater mInflater;
public interface OnItemClickLister {
void onItemClick(View view, int position);
}
private OnItemClickLister mOnItemClickLister;
public void setOnItemClickLister(OnItemClickLister lister) {
this.mOnItemClickLister = lister;
}
public RecommendDicussAdapter(List<RecommendedDiscuss> mDatas, Context mContext) {
this.mContext = mContext;
this.mDatas = mDatas;
mInflater = LayoutInflater.from(mContext);
}
@Override
public RecommendDicussViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mInflater.inflate(R.layout.item_discuss_list,parent,false);
RecommendDicussViewHolder viewHolder= new RecommendDicussViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(RecommendDicussViewHolder holder, int position) {
RecommendedDiscuss reconmmendDicuss=mDatas.get(position);
String user_name=reconmmendDicuss.getUser_name();
String reply_user_name=reconmmendDicuss.getReply_user_name();
// String all_content = "";
String content=reconmmendDicuss.getContent();
// holder.discuss_tv.setText(content);
MoonUtil.SetDicuss(mContext,holder.discuss_tv,content,user_name,R.color.default_text_color,reply_user_name, ImageSpan.ALIGN_BOTTOM);
setUpItemEvent(holder);
}
@Override
public int getItemCount() {
if(mDatas.size()>5){
return 5;
}else {
return mDatas.size();
}
}
/**
* 添加股据到指定位置
* @param pos 数据添加的位置
* @param obj 数据
*/
public void addData(int pos,RecommendedDiscuss obj){
mDatas.add(obj);
notifyItemInserted(pos);
}
/**
* 删除股票到指定位置
* @param pos
*/
public void deleteData(int pos){
mDatas.remove(pos);
notifyItemRemoved(pos);
}
public void updateDate(List<RecommendedDiscuss> mDatas) {
this.mDatas = mDatas;
notifyDataSetChanged();
}
/**
* 给item添加监听
* @param holder
*/
protected void setUpItemEvent(final RecommendDicussViewHolder holder){
if(mOnItemClickLister!=null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemClick(holder.itemView,layoutPosition);
}
});
}
}
}
class RecommendDicussViewHolder extends RecyclerView.ViewHolder{
TextView discuss_tv;
public RecommendDicussViewHolder(View itemView) {
super(itemView);
discuss_tv=(TextView)itemView.findViewById(R.id.item_dicuss_tv);
}
}
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydl_image.transform.CropSquareTransformation;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.RecommendTopic;
import com.ydl.ydlcommon.view.widgets.RoundImageView;
import java.util.List;
/**
* 推荐话题适配器
* Created by xiongyu on 2017/3/14.
*/
public class RecommendTopicAdapter extends RecyclerView.Adapter<RecommendTopicViewHolder> {
protected Context mContext;
protected List<RecommendTopic> mDatas;
protected LayoutInflater mInflater;
public interface OnItemClickLister {
void onItemClick(View view, int position);
}
private OnItemClickLister mOnItemClickLister;
public void setOnItemClickLister(OnItemClickLister lister) {
this.mOnItemClickLister = lister;
}
public RecommendTopicAdapter(List<RecommendTopic> mDatas, Context mContext) {
this.mContext = mContext;
this.mDatas = mDatas;
mInflater = LayoutInflater.from(mContext);
}
@Override
public RecommendTopicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mInflater.inflate(R.layout.item_recommend_topic,parent,false);
RecommendTopicViewHolder viewHolder= new RecommendTopicViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(RecommendTopicViewHolder holder, int position) {
// holder.item_recommend_topic_rel.getBackground().setAlpha(120);
RecommendTopic recommendTopic=mDatas.get(position);
String img_url=recommendTopic.getImg_bg_url();
String topic_title=recommendTopic.getTopic_title();
GlideApp.with(mContext)
.load(img_url)
.error(R.drawable.default_img)
.transform(new CropSquareTransformation(mContext))//裁剪正方形
.override(270, 150)
.centerCrop()
.into(holder.topic_iv);
holder.topic_title_tv.setText(topic_title);
setUpItemEvent(holder);
}
@Override
public int getItemCount() {
return mDatas.size();
}
/**
* 添加股据到指定位置
* @param pos 数据添加的位置
* @param recommendtopic 数据
*/
public void addData(int pos,RecommendTopic recommendtopic){
mDatas.add(recommendtopic);
notifyItemInserted(pos);
}
/**
* 删除股票到指定位置
* @param pos
*/
public void deleteData(int pos){
mDatas.remove(pos);
notifyItemRemoved(pos);
}
/**
* 给item添加监听
* @param holder
*/
protected void setUpItemEvent(final RecommendTopicViewHolder holder){
if(mOnItemClickLister!=null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemClick(holder.itemView,layoutPosition);
}
});
}
}
}
class RecommendTopicViewHolder extends RecyclerView.ViewHolder{
RoundImageView topic_iv;
TextView topic_title_tv;
// RelativeLayout item_recommend_topic_rel;
public RecommendTopicViewHolder(View itemView) {
super(itemView);
// item_recommend_topic_rel=(RelativeLayout) itemView.findViewById(item_recommend_topic_rel);
topic_iv=(RoundImageView)itemView.findViewById(R.id.item_recommend_topic_iv);
topic_title_tv=(TextView)itemView.findViewById(R.id.item_recommend_topic_tv);
}
}
\ No newline at end of file
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.ydl.ydl_image.module.GlideApp;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.RecommendTrendImage;
import java.util.List;
/**
* Created by xiongyu on 2017/3/14.
*/
public class RecommendTrendImgAdapter extends RecyclerView.Adapter<RecommendTrendImgViewHolder> {
private static final String TAG = "RecommendTrendImgAdapte";
protected Context mContext;
protected List<RecommendTrendImage> mDatas,mDatas1;
private String trend_id;
protected LayoutInflater mInflater;
public interface OnItemClickLister {
void onItemClick(View view, int position);
}
private OnItemClickLister mOnItemClickLister;
public void setOnItemClickLister(OnItemClickLister lister) {
this.mOnItemClickLister = lister;
}
public RecommendTrendImgAdapter(List<RecommendTrendImage> mDatas, List<RecommendTrendImage> mDatas1, Context mContext, String trend_id) {
this.mContext = mContext;
this.mDatas = mDatas;
this.mDatas1=mDatas1;
this.trend_id=trend_id;
mInflater = LayoutInflater.from(mContext);
}
@Override
public RecommendTrendImgViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=null;
view=mInflater.inflate(R.layout.item_recommend_trend_img,parent,false);
RecommendTrendImgViewHolder viewHolder= new RecommendTrendImgViewHolder(view);
return viewHolder;
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onBindViewHolder(RecommendTrendImgViewHolder holder, final int position) {
RecommendTrendImage trendImage=mDatas.get(position);
String img_url=trendImage.getImage_url();
if(!"no".equals(img_url)){
GlideApp.with(mContext)
.load(img_url)
// .override(width,width)
.error(R.drawable.default_img)
.centerCrop()
// .bitmapTransform(new CropSquareTransformation(mContext))//裁剪正方形
.into(holder.trend_img1);
}
setUpItemEvent(holder);
}
@Override
public int getItemCount() {
if(mDatas.size()>3){
return 3;
}else {
return mDatas.size();
}
}
public void updateDate(List<RecommendTrendImage> mDatas, List<RecommendTrendImage> mDatas1) {
this.mDatas = mDatas;
this.mDatas1=mDatas1;
notifyDataSetChanged();
}
/**
* 给item添加监听
* @param holder
*/
protected void setUpItemEvent(final RecommendTrendImgViewHolder holder){
if(mOnItemClickLister!=null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemClick(holder.itemView,layoutPosition);
}
});
}
}
}
class RecommendTrendImgViewHolder extends RecyclerView.ViewHolder{
ImageView trend_img1;
// trend_img2,trend_img3;
public RecommendTrendImgViewHolder(View itemView) {
super(itemView);
trend_img1=(ImageView)itemView.findViewById(R.id.item_reconmmend_trend_img_iv1);
// trend_img2=(ImageView)itemView.findViewById(R.id.item_reconmmend_trend_img_iv2);
}
}
\ No newline at end of file
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.RecommendTopic;
import java.util.List;
/**
* Created by xiongyu on 2017/3/14.
*/
public class SelectTopicAdapter extends RecyclerView.Adapter<SelectTopiViewHolder> {
protected Context mContext;
protected List<RecommendTopic> mDatas;
protected LayoutInflater mInflater;
public interface OnItemClickLister {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickLister mOnItemClickLister;
public void setOnItemClickLister(OnItemClickLister lister) {
this.mOnItemClickLister = lister;
}
public SelectTopicAdapter(List<RecommendTopic> mDatas, Context mContext) {
this.mContext = mContext;
this.mDatas = mDatas;
mInflater = LayoutInflater.from(mContext);
}
@Override
public SelectTopiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mInflater.inflate(R.layout.item_select_topic,parent,false);
SelectTopiViewHolder viewHolder= new SelectTopiViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(SelectTopiViewHolder holder, int position) {
RecommendTopic Topic=mDatas.get(position);
String topic_title=Topic.getTopic_title();
holder.topic_title_tv.setText(topic_title);
setUpItemEvent(holder);
}
@Override
public int getItemCount() {
return mDatas.size();
}
/**
* 添加股据到指定位置
* @param pos 数据添加的位置
* @param obj 数据
*/
public void addData(int pos,RecommendTopic obj){
mDatas.add(obj);
notifyItemInserted(pos);
}
/**
* 删除股票到指定位置
* @param pos
*/
public void deleteData(int pos){
mDatas.remove(pos);
notifyItemRemoved(pos);
}
/**
* 给item添加监听
* @param holder
*/
protected void setUpItemEvent(final SelectTopiViewHolder holder){
if(mOnItemClickLister!=null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemClick(holder.itemView,layoutPosition);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int layoutPosition=holder.getLayoutPosition();
mOnItemClickLister.onItemLongClick(holder.itemView,layoutPosition);
return false;
}
});
}
}
}
class SelectTopiViewHolder extends RecyclerView.ViewHolder{
TextView topic_title_tv;
public SelectTopiViewHolder(View itemView) {
super(itemView);
topic_title_tv=(TextView)itemView.findViewById(R.id.item_select_topic_title_tv);
}
}
\ No newline at end of file
package com.yidianling.dynamic.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.ydl.ydl_image.module.GlideApp;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.TopicDetailBean;
import java.util.ArrayList;
import java.util.List;
/**
* 话题详情发帖用户头像
* Created by xiongyu on 2017/3/14.
*/
public class TopicDetailMemberAdapter extends RecyclerView.Adapter<TopicDetailMemberViewHolder> {
private static final String TAG = "TopicDetailMemberAdapter";
protected Context mContext;
protected List<TopicDetailBean.Member> mDatas;
protected LayoutInflater mInflater;
public interface OnItemClickLister {
void onItemClick(View view, int position);
}
public List<TopicDetailBean.Member> getDatas() {
return mDatas;
}
public void addData(int index,TopicDetailBean.Member data) {
if (data == null) {
return;
}
if (mDatas == null) {
mDatas = new ArrayList<TopicDetailBean.Member>();
}
mDatas.add(index,data);
notifyItemRangeChanged(index, mDatas.size()-1);
}
public void removeData(TopicDetailBean.Member data) {
if (mDatas==null||mDatas.size()==0){
return;
}
mDatas.remove(data);
notifyDataSetChanged();
}
public void removeData(int index) {
LogUtil.d("index: " + index + " data size: " + mDatas.size());
if (mDatas == null) return;
mDatas.remove(index);
notifyItemRemoved(index);
notifyItemRangeChanged(index, mDatas.size()); //解决notifyItemRemoved后数据错乱
}
public void addDatas(List<TopicDetailBean.Member> datas) {
mDatas.addAll(datas);
notifyItemRangeChanged(mDatas.size() - datas.size(), datas.size());
}
public void setDatas(List<TopicDetailBean.Member> datas) {
if (datas != null) {
mDatas = datas;
notifyDataSetChanged();
}
}
private OnItemClickLister mOnItemClickLister;
public void setOnItemClickLister(OnItemClickLister lister) {
this.mOnItemClickLister = lister;
}
public TopicDetailMemberAdapter(List<TopicDetailBean.Member> mDatas, Context mContext) {
this.mContext = mContext;
this.mDatas = mDatas;
mInflater = LayoutInflater.from(mContext);
}
public TopicDetailMemberAdapter(Context mContext) {
this(new ArrayList<>(), mContext);
}
@Override
public TopicDetailMemberViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
view = mInflater.inflate(R.layout.item_topicdetail_member_head, parent, false);
TopicDetailMemberViewHolder viewHolder = new TopicDetailMemberViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(TopicDetailMemberViewHolder holder, final int position) {
TopicDetailBean.Member topicDetailMemberHead = mDatas.get(position);
String img_url = topicDetailMemberHead.head;
GlideApp.with(mContext)
.load(img_url)
.error(R.drawable.head_place_hold_pic)
.circleCrop()
.placeholder(R.drawable.head_place_hold_pic)
.error(R.drawable.head_place_hold_pic)
.into(holder.item_topic_member_head_iv);
setUpItemEvent(holder);
}
@Override
public int getItemCount() {
return mDatas.size();
}
/**
* 给item添加监听
*
* @param holder
*/
protected void setUpItemEvent(final TopicDetailMemberViewHolder holder) {
if (mOnItemClickLister != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnItemClickLister.onItemClick(holder.itemView, layoutPosition);
}
});
}
}
}
class TopicDetailMemberViewHolder extends RecyclerView.ViewHolder {
ImageView item_topic_member_head_iv;
public TopicDetailMemberViewHolder(View itemView) {
super(itemView);
item_topic_member_head_iv = (ImageView) itemView.findViewById(R.id.item_topic_member_head_iv);
}
}
\ No newline at end of file
package com.yidianling.dynamic.bean;
import com.flyco.tablayout.listener.CustomTabEntity;
/**
* @author jiucheng
* @描述:
* @Copyright Copyright (c) 2018
* @Company 壹点灵
* @date 2018/7/27
*/
public class TrendTabEntity implements CustomTabEntity {
public String title;
public int selectedIcon;
public int unSelectedIcon;
public TrendTabEntity(String title, int selectedIcon, int unSelectedIcon) {
this.title = title;
this.selectedIcon = selectedIcon;
this.unSelectedIcon = unSelectedIcon;
}
@Override
public String getTabTitle() {
return title;
}
@Override
public int getTabSelectedIcon() {
return selectedIcon;
}
@Override
public int getTabUnselectedIcon() {
return unSelectedIcon;
}
}
package com.yidianling.dynamic.common.behavior;
import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* @author yuanwai
* @描述:
* @Copyright Copyright (c) 2018
* @Company 壹点灵
* @date 2018/8/5 0005
*/
public class AppBarLayoutBehavior extends AppBarLayout.Behavior {
private static final int TYPE_FLING = 1;
private boolean isFlinging;
private boolean shouldBlockNestedScroll;
public AppBarLayoutBehavior() {
}
public AppBarLayoutBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
shouldBlockNestedScroll = false;
if (isFlinging) {
shouldBlockNestedScroll = true;
}
return super.onInterceptTouchEvent(parent, child, ev);
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
//注意看ViewCompat.TYPE_TOUCH
//返回1时,表示当前target处于非touch的滑动,
//该bug的引起是因为appbar在滑动时,CoordinatorLayout内的实现NestedScrollingChild2接口的滑动子类还未结束其自身的fling
//所以这里监听子类的非touch时的滑动,然后block掉滑动事件传递给AppBarLayout
if (type == TYPE_FLING) {
isFlinging = true;
}
if (!shouldBlockNestedScroll) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
}
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int
dxUnconsumed, int dyUnconsumed, int type) {
if (!shouldBlockNestedScroll) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
}
}
@Override
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout abl, View target, int type) {
super.onStopNestedScroll(coordinatorLayout, abl, target, type);
isFlinging = false;
shouldBlockNestedScroll = false;
}
}
package com.yidianling.dynamic.common.behavior;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.util.AttributeSet;
import android.view.View;
/**
<<<<<<< HEAD
* Created by harvie on 2017/10/11 0011.
=======
* Created by Jim on 2017/10/30 0030.
>>>>>>> trendsRebuild
*/
public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
/**
* 因为是在XML中使用app:layout_behavior定义静态的这种行为,
* 必须实现一个构造函数使布局的效果能够正常工作。
* 否则 Could not inflate Behavior subclass error messages.
*
* @param context
* @param attrs
*/
public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
super();
}
/**
* 处理垂直方向上的滚动事件
*
* @param coordinatorLayout
* @param child
* @param directTargetChild
* @param target
* @param nestedScrollAxes
* @return
*/
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
nestedScrollAxes);
}
/**
* 检查Y的位置,并决定按钮是否动画进入或退出
*
* @param coordinatorLayout
* @param child
* @param target
* @param dxConsumed
* @param dyConsumed
* @param dxUnconsumed
* @param dyUnconsumed
*/
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child,
View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
dyUnconsumed);
if (dyConsumed > 10 && child.getVisibility() == View.VISIBLE) {
// User scrolled down and the FAB is currently visible -> hide the FAB
//执行隐藏的动画
hide(child);
} else if (dyConsumed < -10 && child.getVisibility() != View.VISIBLE) {
// User scrolled up and the FAB is currently not visible -> show the FAB
//执行显示的动画
show(child);
}
}
/**
* 显示的动画
*/
private void show(final View view) {
view.animate().cancel();
// If the view isn't visible currently, we'll animate it from a single pixel
view.setAlpha(0f);
view.setScaleY(0f);
view.setScaleX(0f);
view.animate()
.scaleX(1f)
.scaleY(1f)
.alpha(1f)
.setDuration(200)
.setInterpolator(new LinearOutSlowInInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
view.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {
}
});
}
/**
* 隐藏的动画
*/
private void hide(final View view) {
view.animate().cancel();
view.animate()
.scaleX(0f)
.scaleY(0f)
.alpha(0f)
.setDuration(200)
.setInterpolator(new FastOutLinearInInterpolator())
.setListener(new AnimatorListenerAdapter() {
private boolean mCancelled;
@Override
public void onAnimationStart(Animator animation) {
view.setVisibility(View.VISIBLE);
mCancelled = false;
}
@Override
public void onAnimationCancel(Animator animation) {
mCancelled = true;
}
@Override
public void onAnimationEnd(Animator animation) {
if (!mCancelled) {
view.setVisibility(View.INVISIBLE);
}
}
});
}
}
package com.yidianling.dynamic.common.behavior;
import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.View;
/**
* 话题详情behavior
* Created by hgw on 2017/5/15.
*/
public class TopicDetailBehavior extends CoordinatorLayout.Behavior<View>{
public TopicDetailBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency instanceof AppBarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
float translationY = Math.abs(dependency.getTop());//获取更随布局的顶部位置
child.setTranslationY(translationY);
return true;
}
}
package com.yidianling.dynamic.common.browsePictures;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ydl.ydl_image.module.GlideApp;
import com.yidianling.dynamic.DynamicConstants;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.common.tool.DownLoadImageService;
import com.yidianling.dynamic.common.tool.ImageDownLoadCallBack;
import com.ydl.ydlcommon.base.BaseActivity;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
/**
* 预览大图 2 集合范型为String
*/
public class BrowsePicturesActivity2 extends BaseActivity implements ViewPager.OnPageChangeListener {
int iposition;
private ArrayList<String> trendImages;
private ViewPager browse_pictures_vp;
private ImageView back_iv;
private TextView title_tv,save_tv;
String browse_type;
/**
* 装ImageView数组
*/
private List<PhotoView> mImageViews;
MyAdapter myAdapter;
// LodingDialog lodingDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_pictures);
browse_pictures_vp=(ViewPager) findViewById(R.id.browse_pictures_vp);
back_iv=(ImageView)findViewById(R.id.browse_pictures_back_iv);
title_tv=(TextView)findViewById(R.id.browse_pictures_num_tv);
save_tv=(TextView)findViewById(R.id.browse_pictures_save_tv);
initWindows();
Intent intent = getIntent();
iposition=intent.getIntExtra("position",0);
browse_type=intent.getStringExtra("browse_type");
trendImages=intent.getStringArrayListExtra("allTrendImages");
if("browse".equals(browse_type)){
save_tv.setText("保存");
}else if("preview".equals(browse_type)){
save_tv.setText("删除");
}
//将图片装载到数组中
mImageViews = new ArrayList<PhotoView>();
for(int i=0; i<trendImages.size(); i++){
PhotoView imageView = new PhotoView(this);
mImageViews.add(imageView);
}
back_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
save_tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if("browse".equals(browse_type)){//保存
DownLoadImageService downloadService=new DownLoadImageService(BrowsePicturesActivity2.this, trendImages.get(iposition), new ImageDownLoadCallBack() {
@Override
public void onDownLoadSuccess(File file) {
}
@Override
public void onDownLoadSuccess(Bitmap bitmap) {
mHandler.sendEmptyMessage(DynamicConstants.REQUEST_SAVE_IMG_SUCCESS);
}
@Override
public void onDownLoadFailed() {
mHandler.sendEmptyMessage(DynamicConstants.REQUEST_SAVE_IMG_FAIL);
}
});
new Thread(downloadService).start();
}else if("preview".equals(browse_type)){//删除
if(trendImages.size()>1){
if(iposition<trendImages.size()-1){
myAdapter.removie(iposition);
title_tv.setText((iposition+1)+"/"+trendImages.size());
}else {
myAdapter.removie(iposition);
title_tv.setText((iposition+1)+"/"+trendImages.size());
}
}else {
trendImages.clear();
mImageViews.clear();
finish();
}
}
}
});
title_tv.setText((iposition+1)+"/"+trendImages.size());
//设置Adapter
if(myAdapter==null){
myAdapter=new MyAdapter(this,mImageViews,trendImages);
}else {
myAdapter.notifyDataSetChanged();
}
browse_pictures_vp.setAdapter(myAdapter);
//设置监听,主要是设置点点的背景
browse_pictures_vp.setOnPageChangeListener(this);
//设置ViewPager的默认项, 设置为长度的100倍,这样子开始就能往左滑动
browse_pictures_vp.setCurrentItem(iposition);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
iposition=position;
title_tv.setText((iposition+1)+"/"+trendImages.size());
// if (lodingDialog == null) {
// lodingDialog = LodingDialog.getInstance(BrowsePicturesActivity2.this);
// lodingDialog.setMessage("加载中");
// lodingDialog.setSpinnerType(LodingDialog.SIMPLE_ROUND_SPINNER);
// lodingDialog.show();
// }
}
@Override
public void onPageScrollStateChanged(int state) {
// if (lodingDialog != null) {
// lodingDialog.dismiss();
// lodingDialog = null;
// }
}
private void initWindows() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
// window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DynamicConstants.REQUEST_SAVE_IMG_SUCCESS:
Toast.makeText(BrowsePicturesActivity2.this,"保存成功",Toast.LENGTH_SHORT).show();
break;
case DynamicConstants.REQUEST_SAVE_IMG_FAIL:
Toast.makeText(BrowsePicturesActivity2.this,"保存失败",Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected int layoutResId() {
return 0;
}
@Override
protected void initDataAndEvent() {
}
public class MyAdapter extends PagerAdapter {
private Context mContext;
private List<PhotoView> mDatas;
private List<String> mImages;
public MyAdapter(Context mContext, List<PhotoView> mDatas, List<String> mImages) {
this.mContext = mContext;
this.mDatas = mDatas;
this.mImages = mImages;
}
@Override
public int getCount() {
return mDatas.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void destroyItem(View container, int position, Object object) {
View view = (View)object;
((ViewPager) container).removeView(view);
view = null;
// ((ViewPager)container).removeView((View) mDatas.get(position));
}
public void updateDate(List<PhotoView> datas) {
this.mDatas = datas;
notifyDataSetChanged();
}
public void removie(int p) {
mImages.remove(p);
mDatas.remove(p);
notifyDataSetChanged();
}
@Override
public int getItemPosition(Object object) {
return FragmentPagerAdapter.POSITION_NONE;
}
// /**
// * 载入图片进去,用当前的position 除以 图片数组长度取余数是关键
// */
// @Override
// public Object instantiateItem(View container, int position) {
// ((ViewPager)container).addView(mDatas.get(position % mDatas.size()), 0);
// return mDatas.get(position % mDatas.size());
// }
@Override
public Object instantiateItem(View container, int position) {
GlideApp.with(mContext)
.load(mImages.get(position))
.error(R.drawable.default_img)
.into(mDatas.get(position));
mDatas.get(position).setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
@Override
public void onPhotoTap(View view, float x, float y) {
finish();
}
});
((ViewPager)container).addView(mDatas.get(position), 0);
// if (lodingDialog != null) {
// lodingDialog.dismiss();
// lodingDialog = null;
// }
return mDatas.get(position);
}
@Override
public Parcelable saveState() {
return null;
}
}
}
package com.yidianling.dynamic.common.emoji;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.ydl.ydlcommon.utils.emoji.EmojiManager;
import com.yidianling.dynamic.R;
public class EmojiAdapter extends BaseAdapter {
private Context context;
private int startIndex;
public EmojiAdapter(Context mContext, int startIndex) {
this.context = mContext;
this.startIndex = startIndex;
}
public int getCount() {
int count = EmojiManager.getDisplayCount() - startIndex + 1;
count = Math.min(count, EmoticonView.EMOJI_PER_PAGE + 1);
return count;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return startIndex + position;
}
@SuppressLint({ "ViewHolder", "InflateParams" })
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(context).inflate(R.layout.nim_emoji_item, null);
ImageView emojiThumb = (ImageView) convertView.findViewById(R.id.imgEmoji);
int count = EmojiManager.getDisplayCount();
int index = startIndex + position;
if (position == EmoticonView.EMOJI_PER_PAGE || index == count) {
emojiThumb.setBackgroundResource(R.drawable.nim_emoji_del);
} else if (index < count) {
emojiThumb.setBackgroundDrawable(EmojiManager.getDisplayDrawable(context, index));
}
return convertView;
}
}
\ No newline at end of file
package com.yidianling.dynamic.common.emoji;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.ydl.ydlcommon.utils.ScreenUtil;
import com.ydl.ydlcommon.utils.bitmap.BitmapUtils;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.common.view.CheckedImageButton;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* 贴图表情选择控件
*/
public class EmoticonPickerView extends LinearLayout implements IEmoticonCategoryChanged {
private Context context;
private IEmoticonSelectedListener listener;
private boolean loaded = false;
private boolean withSticker;
private EmoticonView gifView;
private ViewPager currentEmojiPage;
private LinearLayout pageNumberLayout;//页面布局
private HorizontalScrollView scrollView;
private LinearLayout tabView;
private int categoryIndex;
private Handler uiHandler;
public EmoticonPickerView(Context context) {
super(context);
init(context);
}
public EmoticonPickerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public EmoticonPickerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
this.context = context;
this.uiHandler = new Handler(context.getMainLooper());
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.nim_emoji_layout, this);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
setupEmojView();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
public void show(IEmoticonSelectedListener listener) {
setListener(listener);
if (loaded)
return;
loadStickers();
loaded = true;
show();
}
public void setListener(IEmoticonSelectedListener listener) {
if (listener != null) {
this.listener = listener;
} else {
LogUtil.i("sticker", "listener is null");
}
}
protected void setupEmojView() {
currentEmojiPage = (ViewPager) findViewById(R.id.scrPlugin);
pageNumberLayout = (LinearLayout) findViewById(R.id.layout_scr_bottom);
tabView = (LinearLayout) findViewById(R.id.emoj_tab_view);
scrollView = (HorizontalScrollView) findViewById(R.id.emoj_tab_view_container);
findViewById(R.id.top_divider_line).setVisibility(View.VISIBLE);
}
// 添加各个tab按钮
OnClickListener tabCheckListener = new OnClickListener() {
@Override
public void onClick(View v) {
onEmoticonBtnChecked(v.getId());
}
};
private void loadStickers() {
if (!withSticker) {
scrollView.setVisibility(View.GONE);
return;
}
final StickerManager manager = StickerManager.getInstance();
tabView.removeAllViews();
int index = 0;
// emoji表情
CheckedImageButton btn = addEmoticonTabBtn(index++, tabCheckListener);
btn.setNormalImageId(R.drawable.nim_emoji_icon_inactive);
btn.setCheckedImageId(R.drawable.nim_emoji_icon);
// 贴图
List<StickerCategory> categories = manager.getCategories();
for (StickerCategory category : categories) {
btn = addEmoticonTabBtn(index++, tabCheckListener);
setCheckedButtomImage(btn, category);
}
}
private CheckedImageButton addEmoticonTabBtn(int index, OnClickListener listener) {
CheckedImageButton emotBtn = new CheckedImageButton(context);
emotBtn.setNormalBkResId(R.drawable.nim_sticker_button_background_normal_layer_list);
emotBtn.setCheckedBkResId(R.drawable.nim_sticker_button_background_pressed_layer_list);
emotBtn.setId(index);
emotBtn.setOnClickListener(listener);
emotBtn.setScaleType(ImageView.ScaleType.FIT_CENTER);
emotBtn.setPaddingValue(ScreenUtil.dip2px(7));
final int emojiBtnWidth = ScreenUtil.dip2px(50);
final int emojiBtnHeight = ScreenUtil.dip2px(44);
tabView.addView(emotBtn);
ViewGroup.LayoutParams emojBtnLayoutParams = emotBtn.getLayoutParams();
emojBtnLayoutParams.width = emojiBtnWidth;
emojBtnLayoutParams.height = emojiBtnHeight;
emotBtn.setLayoutParams(emojBtnLayoutParams);
return emotBtn;
}
private void setCheckedButtomImage(CheckedImageButton btn, StickerCategory category) {
try {
InputStream is = category.getCoverNormalInputStream(context);
if (is != null) {
Bitmap bmp = BitmapUtils.decode(is);
btn.setNormalImage(bmp);
is.close();
}
is = category.getCoverPressedInputStream(context);
if (is != null) {
Bitmap bmp = BitmapUtils.decode(is);
btn.setCheckedImage(bmp);
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void onEmoticonBtnChecked(int index) {
updateTabButton(index);
showEmotPager(index);
}
private void updateTabButton(int index) {
for (int i = 0; i < tabView.getChildCount(); ++i) {
View child = tabView.getChildAt(i);
if (child instanceof FrameLayout) {
child = ((FrameLayout) child).getChildAt(0);
}
if (child != null && child instanceof CheckedImageButton) {
CheckedImageButton tabButton = (CheckedImageButton) child;
if (tabButton.isChecked() && i != index) {
tabButton.setChecked(false);
} else if (!tabButton.isChecked() && i == index) {
tabButton.setChecked(true);
}
}
}
}
private void showEmotPager(int index) {
if (gifView == null) {
gifView = new EmoticonView(context, listener, currentEmojiPage, pageNumberLayout);
gifView.setCategoryChangCheckedCallback(this);
}
gifView.showStickers(index);
}
private void showEmojiView() {
if (gifView == null) {
gifView = new EmoticonView(context, listener, currentEmojiPage, pageNumberLayout);
}
gifView.showEmojis();
}
private void show() {
if (listener == null) {
LogUtil.i("sticker", "show picker view when listener is null");
}
if (!withSticker) {
showEmojiView();
} else {
onEmoticonBtnChecked(0);
setSelectedVisible(0);
}
}
private void setSelectedVisible(final int index) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
if (scrollView.getChildAt(0).getWidth() == 0) {
uiHandler.postDelayed(this, 100);
}
int x = -1;
View child = tabView.getChildAt(index);
if (child != null) {
if (child.getRight() > scrollView.getWidth()) {
x = child.getRight() - scrollView.getWidth();
}
}
if (x != -1) {
scrollView.smoothScrollTo(x, 0);
}
}
};
uiHandler.postDelayed(runnable, 100);
}
@Override
public void onCategoryChanged(int index) {
if (categoryIndex == index) {
return;
}
categoryIndex = index;
updateTabButton(index);
}
public void setWithSticker(boolean withSticker) {
this.withSticker = withSticker;
}
}
package com.yidianling.dynamic.common.emoji;
public interface IEmoticonCategoryChanged {
void onCategoryChanged(int index);
}
\ No newline at end of file
package com.yidianling.dynamic.common.emoji;
public interface IEmoticonSelectedListener {
void onEmojiSelected(String key);
void onStickerSelected(String categoryName, String stickerName);
}
\ No newline at end of file
package com.yidianling.dynamic.common.emoji;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ydl.ydl_image.module.GlideApp;
import com.yidianling.dynamic.R;
/**
* 每屏显示的贴图
*/
public class StickerAdapter extends BaseAdapter {
private Context context;
private StickerCategory category;
private int startIndex;
public StickerAdapter(Context mContext, StickerCategory category, int startIndex) {
this.context = mContext;
this.category = category;
this.startIndex = startIndex;
}
public int getCount() {//获取每一页的数量
int count = category.getStickers().size() - startIndex;
count = Math.min(count, EmoticonView.STICKER_PER_PAGE);
return count;
}
@Override
public Object getItem(int position) {
return category.getStickers().get(startIndex + position);
}
@Override
public long getItemId(int position) {
return startIndex + position;
}
public View getView(int position, View convertView, ViewGroup parent) {
StickerViewHolder viewHolder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.nim_sticker_picker_view, null);
viewHolder = new StickerViewHolder();
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.sticker_thumb_image);
viewHolder.descLabel = (TextView) convertView.findViewById(R.id.sticker_desc_label);
convertView.setTag(viewHolder);
} else {
viewHolder = (StickerViewHolder) convertView.getTag();
}
int index = startIndex + position;
if (index >= category.getStickers().size()) {
return convertView;
}
StickerItem sticker = category.getStickers().get(index);
if (sticker == null) {
return convertView;
}
GlideApp.with(context)
.load(StickerManager.getInstance().getStickerUri(sticker.getCategory(), sticker.getName()))
.error(R.drawable.nim_default_img_failed)
.dontAnimate()
.into(viewHolder.imageView);
viewHolder.descLabel.setVisibility(View.GONE);
return convertView;
}
class StickerViewHolder {
public ImageView imageView;
public TextView descLabel;
}
}
\ No newline at end of file
package com.yidianling.dynamic.common.emoji;
import android.content.Context;
import android.content.res.AssetManager;
import com.ydl.ydlcommon.base.BaseApp;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class StickerCategory implements Serializable {
private static final long serialVersionUID = -81692490861539040L;
private String name; // 贴纸包名
private String title; // 显示的标题
private boolean system; // 是否是系统内置表情
private int order = 0; // 默认顺序
private transient List<StickerItem> stickers;
public StickerCategory(String name, String title, boolean system, int order) {
this.title = title;
this.name = name;
this.system = system;
this.order = order;
loadStickerData();
}
public boolean system() {
return system;
}
public void setSystem(boolean system) {
this.system = system;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<StickerItem> getStickers() {
return stickers;
}
public boolean hasStickers() {
return stickers != null && stickers.size() > 0;
}
public InputStream getCoverNormalInputStream(Context context) {
String filename = name + "_s_normal.png";
return makeFileInputStream(context, filename);
}
public InputStream getCoverPressedInputStream(Context context) {
String filename = name + "_s_pressed.png";
return makeFileInputStream(context, filename);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getCount() {
if (stickers == null || stickers.isEmpty()) {
return 0;
}
return stickers.size();
}
public int getOrder() {
return order;
}
private InputStream makeFileInputStream(Context context, String filename) {
try {
if (system) {
AssetManager assetManager = context.getResources().getAssets();
String path = "sticker/" + filename;
return assetManager.open(path);
} else {
// for future
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public List<StickerItem> loadStickerData() {
List<StickerItem> stickers = new ArrayList<>();
AssetManager assetManager = BaseApp.instance.getResources().getAssets();
try {
String[] files = assetManager.list("sticker/" + name);
for (String file : files) {
stickers.add(new StickerItem(name, file));
}
} catch (IOException e) {
e.printStackTrace();
}
this.stickers = stickers;
return stickers;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof StickerCategory)) {
return false;
}
if (o == this) {
return true;
}
StickerCategory r = (StickerCategory) o;
return r.getName().equals(getName());
}
@Override
public int hashCode() {
return name.hashCode();
}
}
package com.yidianling.dynamic.common.emoji;
public class StickerItem {
private String category;//类别名
private String name;
public StickerItem(String category, String name) {
this.category = category;
this.name = name;
}
public String getIdentifier() {
return category + "/" + name;
}
public String getCategory() {
return category;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (o != null && o instanceof StickerItem) {
StickerItem item = (StickerItem) o;
return item.getCategory().equals(category) && item.getName().equals(name);
}
return false;
}
}
package com.yidianling.dynamic.common.emoji;
import android.content.res.AssetManager;
import android.util.Log;
import com.ydl.ydlcommon.base.BaseApp;
import com.ydl.ydlcommon.utils.FileUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 贴图管理类
*/
public class StickerManager {
private static final String TAG = "StickerManager";
private static StickerManager instance;
private static final String CATEGORY_AJMD = "ajmd";
private static final String CATEGORY_XXY = "xxy";
private static final String CATEGORY_LT = "lt";
/**
* 数据源
*/
private List<StickerCategory> stickerCategories = new ArrayList<>();
private Map<String, StickerCategory> stickerCategoryMap = new HashMap<>();
private Map<String, Integer> stickerOrder = new HashMap<>(3);
public static StickerManager getInstance() {
if (instance == null) {
instance = new StickerManager();
}
return instance;
}
public StickerManager() {
initStickerOrder();
loadStickerCategory();
}
public void init() {
Log.i(TAG, "Sticker Manager init...");
}
private void initStickerOrder() {
// 默认贴图顺序
stickerOrder.put(CATEGORY_AJMD, 1);
stickerOrder.put(CATEGORY_XXY, 2);
stickerOrder.put(CATEGORY_LT, 3);
}
private boolean isSystemSticker(String category) {
return CATEGORY_XXY.equals(category) ||
CATEGORY_AJMD.equals(category) ||
CATEGORY_LT.equals(category);
}
private int getStickerOrder(String categoryName) {
if (stickerOrder.containsKey(categoryName)) {
return stickerOrder.get(categoryName);
} else {
return 100;
}
}
private void loadStickerCategory() {
AssetManager assetManager = BaseApp.instance.getResources().getAssets();
try {
String[] files = assetManager.list("sticker");
StickerCategory category;
for (String name : files) {
if (!FileUtils.hasExtentsion(name)) {
category = new StickerCategory(name, name, true, getStickerOrder(name));
stickerCategories.add(category);
stickerCategoryMap.put(name, category);
}
}
// 排序
Collections.sort(stickerCategories, new Comparator<StickerCategory>() {
@Override
public int compare(StickerCategory l, StickerCategory r) {
return l.getOrder() - r.getOrder();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized List<StickerCategory> getCategories() {
return stickerCategories;
}
public synchronized StickerCategory getCategory(String name) {
return stickerCategoryMap.get(name);
}
public String getStickerUri(String categoryName, String stickerName) {
StickerManager manager = StickerManager.getInstance();
StickerCategory category = manager.getCategory(categoryName);
if (category == null) {
return null;
}
if (isSystemSticker(categoryName)) {
if (!stickerName.contains(".png")) {
stickerName += ".png";
}
String path = "sticker/" + category.getName() + "/" + stickerName;
return "file:///android_asset/" + path;
}
return null;
}
}
package com.yidianling.dynamic.common.net;
import android.content.Context;
import com.ydl.ydlcommon.data.http.BaseAPIResponse;
import com.ydl.ydlcommon.data.http.BaseCommand;
import com.ydl.ydlcommon.data.http.BaseResponse;
import com.ydl.ydlcommon.data.http.FormatText;
import com.ydl.ydlcommon.utils.NetworkParamsUtils;
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils;
import com.ydl.ydlnet.YDLHttpUtils;
import com.yidianling.dynamic.model.Command;
import com.yidianling.dynamic.model.CommentBean;
import com.yidianling.dynamic.model.ExpertBuild;
import com.yidianling.dynamic.model.Focus;
import com.yidianling.dynamic.model.MemberInfoBean;
import com.yidianling.dynamic.model.PublishTrendResult;
import com.yidianling.dynamic.model.Reply;
import com.yidianling.dynamic.model.TestDetail;
import com.yidianling.dynamic.model.TopicListDataBean;
import com.yidianling.dynamic.model.TrendsDetailInfoBean;
import com.yidianling.dynamic.model.TrendsListBean;
import com.yidianling.dynamic.model.TrendsReplyBean;
import com.yidianling.dynamic.model.ZanResult;
import com.yidianling.dynamic.thank.data.SendThxWithMoney;
import com.yidianling.dynamic.thank.data.ThxData;
import com.yidianling.dynamic.thank.data.ThxListDate;
import com.yidianling.dynamic.thank.data.ZJservice;
import java.io.File;
import java.util.List;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.RequestBody;
/**
* Created by Jim on 2018/2/5 0005.
*/
public class DynamicApiUtils {
public static void handleError(Context context, Throwable t) {
HttpErrorUtils.Companion.handleError(context, t);
}
public static Map<String, String> getMaps(List<FormatText> list) {
return NetworkParamsUtils.getMaps(list);
}
public static List<FormatText> getPostList(BaseCommand crq) {
return NetworkParamsUtils.getPostList(crq);
}
// 送感谢 (为了获取相关数据)
public static Observable<BaseResponse<ThxData>> getThxHeadData(Command.GetThxHeadDate cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getThxHeadData(getMaps(list));
}
//获取赞列表
public static Observable<BaseResponse<ThxListDate>> getZanList(Command.GetZanList cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getZanList(getMaps(list));
}
//点赞:动态,回帖,个人主页
public static Observable<BaseResponse<ZanResult>> zanAction(Command.ZanAction cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).zanAction(getMaps(list));
}
//获取社区帖子评论详情
public static Observable<BaseResponse<TrendsReplyBean>> trendsReplyInfo(Command.TrendsReplyInfo cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).trendsReplyInfo(getMaps(list));
}
public static Observable<BaseResponse<Object>> visitCounter(Command.UserAndTrendVisitCmd cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).visitCounter(getMaps(list));
}
public static Observable<TrendsListBean> fetchPhpTrendList(Command.TrendListCmd cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).fetchPhpTrendList(getMaps(list));
}
public static Observable<BaseAPIResponse<TrendsListBean>> fetchTrendList(Command.TrendListCmd cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).fetchTrendList(getMaps(list));
}
//个人资料
public static Observable<BaseResponse<MemberInfoBean>> getMemberInfo(Command.MemberInfoCmd cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getMemberInfo(getMaps(list));
}
//关注
public static Observable<BaseResponse<Focus>> focus(Command.FocusCmd cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).focus(getMaps(list));
}
//加入黑名单
public static Observable<BaseResponse<Object>> setBlackCall(Command.SetBlackCall cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).setBlackCall(getMaps(list));
}
// 移出黑名单
public static Observable<BaseResponse<Object>> rmBlack(Command.RmBlack cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).rmBlack(getMaps(list));
}
//获取专家相关信息
public static Observable<BaseResponse<ZJservice>> getService(Command.Service cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getService(getMaps(list));
}
//获取举报理由
public static Observable<BaseResponse> getReportReason(Command.GetReportReason cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getReportReason(getMaps(list));
}
//举报心事或者心事回复(动态)
public static Observable<BaseResponse<Object>> reportWorry(Command.ReportWorry cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).reportWorry(getMaps(list));
}
//发布动态
public static Observable<BaseResponse<PublishTrendResult>> publishTrend(Command.PublishTrend cmd, File... files) {
Map<String, RequestBody> map = NetworkParamsUtils.getFileMaps(cmd, "FILE", files);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).publishTrend(map);
}
//话题列表
public static Observable<BaseResponse<TopicListDataBean>> fetchTopicList(Command.AllTopicCmd cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).fetchTopicList(getMaps(list));
}
/**
* 获取用户信息
*/
public static Observable<BaseResponse<Object>> adClickCount(Command.AdClickCount c) {
List<FormatText> list = getPostList(c);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).adClickCount(getMaps(list));
}
//个人动态
public static Observable<BaseResponse<List<TrendsListBean.Trend>>> getUserTrend(Command.UserTrendCmd cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getUserTrend(getMaps(list));
}
public static Observable<BaseResponse<TestDetail>> fetchTestDetail(Command.FetchTestDetailCommand cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).fetchTestDetail(getMaps(list));
}
//获取社区帖子评论列表 todo php 待修改
public static Observable<BaseResponse<List<CommentBean>>> fetchTrendsComments(Command.TrendsComments cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).fetchTrendsComments(getMaps(list));
}
//帖子或评论删除
public static Observable<BaseResponse<Object>> removeTrendsReply(Command.TrendsReplyDel cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).removeTrendsReply(getMaps(list));
}
//私聊 获取聊天者的订单关系数据
public static Observable<BaseResponse<ExpertBuild>> getExpert(Command.GetExpert cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getExpert(getMaps(list));
}
//获取用户的状态(用户、专家、助理)
public static Observable<BaseAPIResponse<String>> getExpert(String toUid) {
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getUserType(toUid);
}
////私聊 获取聊天者的订单关系数据 -----进入聊天前调用的接口,采用新的java接口,直接php getExpert 接口废弃
public static Observable<BaseResponse<ExpertBuild>> getPersonalChat(String toUid) {
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).getPersonalChat(toUid);
}
//回复盖楼
public static Observable<BaseResponse<Reply>> commitOrReply(Command.CommentOrReply cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).commitOrReply(getMaps(list));
}
//话题/动态详情
public static Observable<BaseAPIResponse<TrendsDetailInfoBean>> fetchTrendsDetailInfo(Command.TrendsInfo cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).fetchTrendsDetailInfo(getMaps(list));
}
//感谢表单提交
public static Observable<BaseResponse<SendThxWithMoney>> submitZan(Command.SubmitZan cmd) {
List<FormatText> list = getPostList(cmd);
return YDLHttpUtils.Companion.obtainApi(NetApiStore.class).submitZan(getMaps(list));
}
}
package com.yidianling.dynamic.common.net;
import com.yidianling.dynamic.model.CommentBean;
import com.yidianling.dynamic.model.ExpertBuild;
import com.yidianling.dynamic.model.Focus;
import com.yidianling.dynamic.model.MemberInfoBean;
import com.yidianling.dynamic.model.PublishTrendResult;
import com.yidianling.dynamic.model.Reply;
import com.yidianling.dynamic.model.TestDetail;
import com.yidianling.dynamic.model.TopicDetailBean;
import com.yidianling.dynamic.model.TopicListDataBean;
import com.yidianling.dynamic.model.TrendsDetailInfoBean;
import com.yidianling.dynamic.model.TrendsListBean;
import com.yidianling.dynamic.model.TrendsReplyBean;
import com.yidianling.dynamic.model.ZanResult;
import com.yidianling.dynamic.thank.data.SendThxWithMoney;
import com.yidianling.dynamic.thank.data.ThxData;
import com.yidianling.dynamic.thank.data.ThxListDate;
import com.yidianling.dynamic.thank.data.ZJservice;
import com.ydl.ydlcommon.data.http.BaseAPIResponse;
import com.ydl.ydlcommon.data.http.BaseResponse;
import java.util.List;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.RequestBody;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.PartMap;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
import static com.ydl.ydlcommon.base.config.AppConfigKt.YDL_DOMAIN;
import static com.ydl.ydlcommon.base.config.AppConfigKt.YDL_DOMAIN_JAVA;
/**
* Created by Jim on 2018/2/5 0005.
*/
public interface NetApiStore {
@FormUrlEncoded
@POST("ask/zan-list")
Observable<BaseResponse<ThxListDate>> getZanList(@FieldMap Map<String, String> params);
// 送感谢 (为了获取相关数据)
@FormUrlEncoded
@POST("ask/zan")
Observable<BaseResponse<ThxData>> getThxHeadData(@FieldMap Map<String, String> params);
//点赞:动态,回帖,个人主页
@FormUrlEncoded
@POST("sq-active/zan")
Observable<BaseResponse<ZanResult>> zanAction(@FieldMap Map<String, String> params);
@FormUrlEncoded
@POST("sq-active/reply-detail")
Observable<BaseResponse<TrendsReplyBean>> trendsReplyInfo(@FieldMap Map<String, String> params);
//用户和动态浏览统计
@FormUrlEncoded
@POST("sq-active/visit-counter")
Observable<BaseResponse<Object>> visitCounter(@FieldMap Map<String, String> params);
//个人资料
@FormUrlEncoded
@POST("sq-active/person")
Observable<BaseResponse<MemberInfoBean>> getMemberInfo(@FieldMap Map<String, String> params);
//关注
@FormUrlEncoded
@POST("sq-active/focus")
Observable<BaseResponse<Focus>> focus(@FieldMap Map<String, String> params);
//移出黑名单
@FormUrlEncoded
@POST("consult/rm-black")
Observable<BaseResponse<Object>> rmBlack(@FieldMap Map<String, String> params);
//加入黑名单
@FormUrlEncoded
@POST("consult/set-black")
Observable<BaseResponse<Object>> setBlackCall(@FieldMap Map<String, String> params);
//获取举报理由
@FormUrlEncoded
@POST("ask/report-reason")
Observable<BaseResponse> getReportReason(@FieldMap Map<String, String> params);
//举报心事或者心事回复(动态)
@FormUrlEncoded
@POST("ask/report")
Observable<BaseResponse<Object>> reportWorry(@FieldMap Map<String, String> params);
//发布动态
@Multipart
@POST("sq-active/publish")
Observable<BaseResponse<PublishTrendResult>> publishTrend(@PartMap Map<String, RequestBody> params);
//话题列表
@FormUrlEncoded
@POST("sq-active/topic-list")
Observable<BaseResponse<TopicListDataBean>> fetchTopicList(@FieldMap Map<String, String> params);
//话题详情
@GET()
@Headers({YDL_DOMAIN + YDL_DOMAIN_JAVA,"Content-Type:application/json"})
Observable<BaseAPIResponse<TopicDetailBean>> getTopicDetail(@Url String url);
//预约下单页面数据
@POST("site/focus-click-counter")
@FormUrlEncoded
Observable<BaseResponse<Object>> adClickCount(@FieldMap Map<String, String> maps);
//动态列表(php) 老的
@FormUrlEncoded
@POST("sq-active/active-list")
Observable<TrendsListBean> fetchPhpTrendList(@FieldMap Map<String, String> params);
//动态列表(java)
@GET("ask/list-old")
@Headers(YDL_DOMAIN + YDL_DOMAIN_JAVA)
Observable<BaseAPIResponse<TrendsListBean>> fetchTrendList(@QueryMap Map<String, String> params);
//个人动态
@FormUrlEncoded
@POST("sq-active/person-active")
Observable<BaseResponse<List<TrendsListBean.Trend>>> getUserTrend(@FieldMap Map<String, String> params);
//获取测试详情
@FormUrlEncoded
@POST("ceshi/detail")
Observable<BaseResponse<TestDetail>> fetchTestDetail(@FieldMap Map<String, String> params);
//获取社区帖子评论列表
@FormUrlEncoded
@POST("sq-active/active-comments")
Observable<BaseResponse<List<CommentBean>>> fetchTrendsComments(@FieldMap Map<String, String> params);
//帖子或评论删除
@FormUrlEncoded
@POST("sq-active/remove")
Observable<BaseResponse<Object>> removeTrendsReply(@FieldMap Map<String, String> params);
//私聊 获取聊天者的订单关系数据
@FormUrlEncoded
@POST("consult/get-expert")
Observable<BaseResponse<ExpertBuild>> getExpert(@FieldMap Map<String, String> params);
//获取用户的状态(用户、专家、助理)
@GET("user/userType")
@Headers(YDL_DOMAIN + YDL_DOMAIN_JAVA)
Observable<BaseAPIResponse<String>> getUserType(@Query("targetUid") String uid);
//私聊 获取聊天者的订单关系数据 -----进入聊天前调用的接口,采用新的java接口,直接php getExpert 接口废弃
@GET("doctor/personalChat")
@Headers(YDL_DOMAIN + YDL_DOMAIN_JAVA)
Observable<BaseResponse<ExpertBuild>> getPersonalChat(@Query("doctorUid") String doctorUid);
//回复盖楼
@FormUrlEncoded
@POST("sq-active/reply")
Observable<BaseResponse<Reply>> commitOrReply(@FieldMap Map<String, String> params);
//动态详情
@GET("ask/detail-old")
@Headers(YDL_DOMAIN + YDL_DOMAIN_JAVA)
Observable<BaseAPIResponse<TrendsDetailInfoBean>> fetchTrendsDetailInfo(@QueryMap Map<String, String> params);
//感谢表单提交
@FormUrlEncoded
@POST("ask/zan-act")
Observable<BaseResponse<SendThxWithMoney>> submitZan(@FieldMap Map<String, String> params);
//获取专家相关信息
@FormUrlEncoded
@POST("doctor/get-service")
Observable<BaseResponse<ZJservice>> getService(@FieldMap Map<String, String> params);
}
\ No newline at end of file
package com.yidianling.dynamic.common.tool
/**
* Created by Jim on 2018/2/5 0005.
*/
/**
* author : Zhangwenchao
* e-mail : zhangwch@yidianling.com
* time : 2017/12/19
*/
class ApiThrowable(var code: Int, var status: Int, msg: String) : Throwable(msg)
\ No newline at end of file
//package com.yidianling.dynamic.common.tool;
//
//import android.content.Context;
//import android.graphics.Bitmap;
//
//import com.bumptech.glide.load.Transformation;
//import com.bumptech.glide.load.engine.Resource;
//import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
//import com.bumptech.glide.load.resource.bitmap.BitmapResource;
//import com.ydl.ydl_image.module.GlideApp;
//
//import java.security.MessageDigest;
//
///**
// * Created by xiongyu on 2017/3/16.
// */
//
//public class CropSquareTransformation implements Transformation<Bitmap> {
//
// private BitmapPool mBitmapPool;
// private int mWidth;
// private int mHeight;
//
// public CropSquareTransformation(Context context) {
// this(GlideApp.get(context).getBitmapPool());
// }
//
// public CropSquareTransformation(BitmapPool pool) {
// this.mBitmapPool = pool;
// }
//
// @Override
// public Resource<Bitmap> transform(Context context, Resource<Bitmap> resource, int outWidth, int outHeight) {
// Bitmap source = resource.get();
// int size = Math.min(source.getWidth(), source.getHeight());
//
// mWidth = (source.getWidth() - size) / 2;
// mHeight = (source.getHeight() - size) / 2;
//
// Bitmap.Config config =
// source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888;
// Bitmap bitmap = mBitmapPool.get(mWidth, mHeight, config);
// if (bitmap == null) {
// bitmap = Bitmap.createBitmap(source, mWidth, mHeight, size, size);
// }
//
// return BitmapResource.obtain(bitmap, mBitmapPool);
// }
//
// @Override
// public void updateDiskCacheKey(MessageDigest messageDigest) {
//
// }
//}
package com.yidianling.dynamic.common.tool;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import com.bumptech.glide.request.target.Target;
import com.ydl.ydl_image.module.GlideApp;
import com.yidianling.common.tools.RxFileTool;
import com.ydl.ydlcommon.utils.StringUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by xiongyu on 2017/3/17.
*/
public class DownLoadImageService implements Runnable {
private String url;
private Context context;
private ImageDownLoadCallBack callBack;
private File currentFile;
public DownLoadImageService(Context context, String url, ImageDownLoadCallBack callBack) {
this.url = url;
this.callBack = callBack;
this.context = context;
}
@Override
public void run() {
File file = null;
Bitmap bitmap = null;
try {
// file = Glide.with(context)
// .load(url)
// .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
// .get();
bitmap = GlideApp.with(context)
.asBitmap()
.load(url)
.into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
if (bitmap != null) {
// 在这里执行图片保存方法
saveImageToGallery(context, bitmap);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// if (file != null) {
// callBack.onDownLoadSuccess(file);
// } else {
// callBack.onDownLoadFailed();
// }
if (bitmap != null && currentFile.exists()) {
callBack.onDownLoadSuccess(bitmap);
} else {
callBack.onDownLoadFailed();
}
}
}
public void saveImageToGallery(Context context, Bitmap bmp) {
// 首先保存图片
String fileName = "trend";
File appDir = new File(RxFileTool.getStorageDirectory(context), fileName);
if (!appDir.exists()) {
appDir.mkdirs();
}
fileName = StringUtils.UrlToString(url);
currentFile = new File(appDir, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(currentFile);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 其次把文件插入到系统图库
// try {
// MediaStore.Images.Media.insertImage(context.getContentResolver(),
// currentFile.getAbsolutePath(), fileName, null);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(currentFile.getPath()))));
}
}
package com.yidianling.dynamic.common.tool;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* * * Created by xiongyu on 2016/2/17.
*/
public class FakeX509TrustManager implements X509TrustManager {
private static TrustManager[] trustManagers;
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
//To change body of implemented methods use File | Settings | File Templates.
}
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
}
public static void allowAllSSL() {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
SSLContext context = null;
if (trustManagers == null) {
trustManagers = new TrustManager[]{new FakeX509TrustManager()};
}
try {
context = SSLContext.getInstance("TLS");
context.init(null, trustManagers, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (
KeyManagementException e
)
{
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
}
\ No newline at end of file
package com.yidianling.dynamic.common.tool;
import android.app.Activity;
import android.widget.ImageView;
import com.lzy.imagepicker.loader.ImageLoader;
import com.ydl.ydl_image.config.ISimpleImageOpConfig;
import com.ydl.ydl_image.config.SimpleImageOpConfiger;
import com.ydl.ydl_image.manager.YDLImageCacheManager;
import com.yidianling.dynamic.R;
/**
* Created by xiongyu on 2017/4/7.
*/
public class GlideImageLoader implements ImageLoader {
@Override
public void displayImage(Activity activity, String path, ImageView imageView, int width, int height) {
showImage(activity,path,imageView,width,height);
}
@Override
public void displayImagePreview(Activity activity, String path, ImageView imageView, int width, int height) {
showImage(activity,path,imageView,width,height);
}
private void showImage(Activity activity, String path, ImageView imageView, int width, int height){
SimpleImageOpConfiger sp = new SimpleImageOpConfiger();
sp.loadingPic = R.drawable.default_img;
sp.errorPic = R.drawable.default_img;
sp.scaleType = ISimpleImageOpConfig.CENTER_CROP;
sp.isCacheOnDisk = false;
YDLImageCacheManager.showImage(activity,path,imageView,width, height,sp);
}
@Override
public void clearMemoryCache() {
}
}
package com.yidianling.dynamic.common.tool;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import com.yidianling.common.tools.RxFileTool;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ImageCompress {
public static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
public static File scal(String path, int size) {
// String path = fileUri.getPath();
File outputFile = new File(path);
if (!outputFile.exists()){
return null;
}
long fileSize = outputFile.length();
final long fileMaxSize = size * 1024;
if (fileSize >= fileMaxSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int height = options.outHeight;
int width = options.outWidth;
double scale = Math.sqrt((float) fileSize / fileMaxSize);
options.outHeight = (int) (height / scale);
options.outWidth = (int) (width / scale);
options.inSampleSize = (int) (scale + 0.5);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
outputFile = new File(PhotoUtil.createImageFile().getPath());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("", "sss ok " + outputFile.length());
if (!bitmap.isRecycled()) {
bitmap.recycle();
} else {
File tempFile = outputFile;
outputFile = new File(PhotoUtil.createImageFile().getPath());
PhotoUtil.copyFileUsingFileChannels(tempFile, outputFile);
}
}
return outputFile;
}
public static File scaln(String path, int size) {
// String path = fileUri.getPath();
File outputFile = new File(path);
// long fileSize = outputFile.length();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap imagebm = BitmapFactory.decodeFile(path);
imagebm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// final long fileMaxSize = size * 1024;
// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > size) {
// 循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();// 重置baos即清空baos
imagebm.compress(Bitmap.CompressFormat.JPEG, options, baos);
// 这里压缩options%,把压缩后的数据存放到baos中
options -= 10;// 每次都减少10
if (options <= 0) {
break;
}
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
// 把压缩后的数据baos存放到ByteArrayInputStream中
// 把ByteArrayInputStream数据生成图片
imagebm = BitmapFactory.decodeStream(isBm, null, null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputFile);
imagebm.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (!imagebm.isRecycled()) {
imagebm.recycle();
} else {
File tempFile = outputFile;
outputFile = new File(PhotoUtil.createImageFile().getPath());
PhotoUtil.copyFileUsingFileChannels(tempFile, outputFile);
}
return outputFile;
}
public static File scaln2(String path, int size) {
Bitmap bm = BitmapFactory.decodeFile(path);
bm=cQuality(bm,size);
File outputFile = null;
try {
outputFile = SaveBitmap(bm,path);
} catch (IOException e) {
e.printStackTrace();
}
return outputFile;
}
public static File SaveBitmap(Bitmap mBitmap, String path) throws IOException {
File file;
RxFileTool.fileExists(path);
File f = new File(path);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file=new File(path);
return file;
}
/**
* 根据bitmap压缩图片质量
*
* @param bitmap 未压缩的bitmap
* @return 压缩后的bitmap
*/
public static Bitmap cQuality(Bitmap bitmap,int size) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int beginRate = 100;
//第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差 ,第三个参数:保存压缩后的数据的流
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
while (bOut.size() / 1024 / 1024 > size) { //如果压缩后大于100Kb,则提高压缩率,重新压缩
beginRate -= 10;
bOut.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
}
ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
if (newBitmap != null) {
return newBitmap;
} else {
return bitmap;
}
}
}
package com.yidianling.dynamic.common.tool;
import android.graphics.Bitmap;
import java.io.File;
/**
* Created by xiongyu on 2017/3/17.
*/
public interface ImageDownLoadCallBack {
void onDownLoadSuccess(File file);
void onDownLoadSuccess(Bitmap bitmap);
void onDownLoadFailed();
}
\ No newline at end of file
package com.yidianling.dynamic.common.tool;
import android.net.Uri;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PhotoUtil {
/**
* 一切都操作uri
* @return
*/
public static Uri createImageFile(){
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = null;
try {
image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
} catch (IOException e) {
e.printStackTrace();
}
// Save a file: path for use with ACTION_VIEW intents
return Uri.fromFile(image);
}
public static void copyFileUsingFileChannels(File source, File dest){
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
inputChannel.close();
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.yidianling.dynamic.common.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageButton;
/**
* 选中图片控件
*/
public class CheckedImageButton extends ImageButton {
private boolean checked;
private int normalBkResId;
private int checkedBkResId;
private Drawable normalImage;
private Drawable checkedImage;
private int leftPadding, topPadding, rightPadding, bottomPadding;
public CheckedImageButton(Context context) {
super(context);
}
public CheckedImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CheckedImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setPaddingValue(int value) {
setPaddingValue(value, value, value, value);
}
public void setPaddingValue(int left, int top, int right, int bottom) {
leftPadding = left;
topPadding = top;
rightPadding = right;
bottomPadding = bottom;
setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean push) {
this.checked = push;
Drawable image = push ? checkedImage : normalImage;
if (image != null) {
updateImage(image);
}
int background = push ? checkedBkResId : normalBkResId;
if (background != 0) {
updateBackground(background);
}
}
public void setNormalBkResId(int normalBkResId) {
this.normalBkResId = normalBkResId;
updateBackground(normalBkResId);
}
public void setCheckedBkResId(int checkedBkResId) {
this.checkedBkResId = checkedBkResId;
}
public void setNormalImageId(int normalResId) {
normalImage = getResources().getDrawable(normalResId);
updateImage(normalImage);
}
public void setCheckedImageId(int pushedResId) {
checkedImage = getResources().getDrawable(pushedResId);
}
public void setNormalImage(Bitmap bitmap) {
this.normalImage = new BitmapDrawable(getResources(), bitmap);
updateImage(this.normalImage);
}
public void setCheckedImage(Bitmap bitmap) {
this.checkedImage = new BitmapDrawable(getResources(), bitmap);
}
private void updateBackground(int resId) {
setBackgroundResource(resId);
setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
// int padding = ScreenUtil.dip2px(7);
// setPadding(padding, padding, padding, padding);
}
private void updateImage(Drawable drawable) {
// setScaleType(ScaleType.FIT_CENTER);
setImageDrawable(drawable);
}
}
package com.yidianling.dynamic.common.view;
import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by xiongyu16609 on 2016/9/4.
*/
public class FullyGridLayoutManager extends GridLayoutManager {
public FullyGridLayoutManager(Context context, int spanCount) {
super(context, spanCount);
}
public FullyGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {
super(context, spanCount, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
int count = getItemCount();
int span = getSpanCount();
for (int i = 0; i < count; i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
if (i % span == 0) {
width = width + mMeasuredDimension[0];
}
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
if (i % span == 0) {
height = height + mMeasuredDimension[1];
}
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
if (position < getItemCount()) {
try {
View view = recycler.getViewForPosition(0);//fix 动态添加时报IndexOutOfBoundsException
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.yidianling.dynamic.common.view;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
public class FullyLinearLayoutManager extends LinearLayoutManager {
// private static final String TAG = FullyLinearLayoutManager.class.getSimpleName();
public FullyLinearLayoutManager(Context context) {
super(context);
}
public FullyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
try {
View view = recycler.getViewForPosition(0);//fix 动态添加时报IndexOutOfBoundsException
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
package com.yidianling.dynamic.common.view;
import com.ydl.ydlcommon.bean.ShareData;
import java.io.Serializable;
/**
* ================================================
* 作 者:廖子尧
* 版 本:1.0
* 创建日期:2016/3/21
* 描 述:
* 修订历史:
* ================================================
*/
public class ImageInfo implements Serializable {
public String thumbnailUrl;
public String bigImageUrl;
public int imageViewHeight;
public int imageViewWidth;
public int imageViewX;
public int imageViewY;
public String imageLinkUrl;
public ShareData mShareData;
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getBigImageUrl() {
return bigImageUrl;
}
public void setBigImageUrl(String bigImageUrl) {
this.bigImageUrl = bigImageUrl;
}
public int getImageViewHeight() {
return imageViewHeight;
}
public void setImageViewHeight(int imageViewHeight) {
this.imageViewHeight = imageViewHeight;
}
public int getImageViewWidth() {
return imageViewWidth;
}
public void setImageViewWidth(int imageViewWidth) {
this.imageViewWidth = imageViewWidth;
}
public int getImageViewX() {
return imageViewX;
}
public void setImageViewX(int imageViewX) {
this.imageViewX = imageViewX;
}
public int getImageViewY() {
return imageViewY;
}
public void setImageViewY(int imageViewY) {
this.imageViewY = imageViewY;
}
@Override
public String toString() {
return "ImageInfo{" +
"imageViewY=" + imageViewY +
", imageViewX=" + imageViewX +
", imageViewWidth=" + imageViewWidth +
", imageViewHeight=" + imageViewHeight +
", bigImageUrl='" + bigImageUrl + '\'' +
", thumbnailUrl='" + thumbnailUrl + '\'' +
'}';
}
}
package com.yidianling.dynamic.common.view;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.TrendsListBean;
import com.yidianling.dynamic.trendsDetail.TrendsDetailActivity;
import java.util.List;
/**
* 为home_loop定制的view
*/
public class LooperTextView extends FrameLayout {
private static final int STATUS_IN = 0;
private static final int STATUS_OUT = 1;
private List<TrendsListBean.ExtData> tipList;
private int curTipIndex = 0;
private long lastTimeMillis;
private static final int ANIM_DELAYED_MILLIONS = 4 * 1000;
/**
* 动画持续时长
*/
private static final int ANIM_DURATION = 1000;
private static final String DEFAULT_TEXT_COLOR = "#2F4F4F";
private static final int DEFAULT_TEXT_SIZE = 16;
private View view_out, view_in;
private TextView content_before_in;
private TextView content_before_out;
private Animation anim_out, anim_in;
private Handler handler = new Handler();
private Runnable repeatCode = new Runnable() {
@Override
public void run() {
updateTipAndPlayAnimation();
handler.postDelayed(repeatCode, ANIM_DELAYED_MILLIONS);
}
};
public LooperTextView(Context context) {
super(context);
initTipFrame();
initAnimation();
}
public LooperTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initTipFrame();
initAnimation();
}
public LooperTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initTipFrame();
initAnimation();
}
private void initTipFrame() {
view_out = newTextView(STATUS_OUT);
view_in = newTextView(STATUS_IN);
addView(view_in);
addView(view_out);
}
private View newTextView(int status) {
View view = LayoutInflater.from(getContext()).inflate(R.layout.looper_item, null, false);
if (status == STATUS_IN) {
content_before_in = (TextView) view.findViewById(R.id.loop_content_before);
} else if (status == STATUS_OUT) {
content_before_out = (TextView) view.findViewById(R.id.loop_content_before);
}
return view;
}
/**
* 将资源图片转换为Drawable对象
*
* @param ResId
* @return
*/
private Drawable loadDrawable(int ResId) {
Drawable drawable = getResources().getDrawable(ResId);
drawable.setBounds(0, 0, drawable.getMinimumWidth() - 10, drawable.getMinimumHeight() - 10);
return drawable;
}
private void initAnimation() {
anim_out = newAnimation(0, -1);
anim_in = newAnimation(1, 0);
anim_in.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
updateViewVisibility();
}
});
}
private Animation newAnimation(float fromYValue, float toYValue) {
Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, fromYValue, Animation.RELATIVE_TO_SELF, toYValue);
anim.setDuration(ANIM_DURATION);
anim.setInterpolator(new DecelerateInterpolator());
return anim;
}
private void updateTipAndPlayAnimationWithCheck() {
if (System.currentTimeMillis() - lastTimeMillis < 1000) {
return;
}
lastTimeMillis = System.currentTimeMillis();
updateTipAndPlayAnimation();
}
private void updateViewVisibility() {
if (curTipIndex % 2 == 0) {
view_out.setVisibility(INVISIBLE);
} else {
view_in.setVisibility(INVISIBLE);
}
}
private void updateTipAndPlayAnimation() {
view_in.setVisibility(VISIBLE);
view_out.setVisibility(VISIBLE);
if (curTipIndex % 2 == 0) {
updateTip(STATUS_OUT);
view_in.startAnimation(anim_out);
view_out.startAnimation(anim_in);
this.bringChildToFront(view_in);
} else {
updateTip(STATUS_IN);
view_out.startAnimation(anim_out);
view_in.startAnimation(anim_in);
this.bringChildToFront(view_out);
}
}
private void updateTip(int status) {
final TrendsListBean.ExtData tip = getNextTip();
if (tip != null) {
if (status == STATUS_IN) {
SpannableString spannableString=new SpannableString("置顶 "+tip.getTitle());
spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FAA05A")), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
content_before_in.setText(spannableString);
view_in.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
TrendsDetailActivity.start(getContext(),Integer.valueOf(tip.getId()),false,false,false,false,0);
}catch (Exception e){
e.printStackTrace();
}
}
});
} else if (status == STATUS_OUT) {
SpannableString spannableString=new SpannableString("置顶 "+tip.getTitle());
spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FAA05A")), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
content_before_out.setText(spannableString);
view_out.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
TrendsDetailActivity.start(getContext(),Integer.valueOf(tip.getId()),false,false,false,false,0);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
}
/**
* 获取下一条消息
*
* @return
*/
private TrendsListBean.ExtData getNextTip() {
if (isListEmpty(tipList)) return null;
return tipList.get(curTipIndex++ % tipList.size());
}
public static boolean isListEmpty(List list) {
return list == null || list.isEmpty();
}
public void setTipList(List<TrendsListBean.ExtData> tipList) {
handler.removeCallbacks(repeatCode);
this.tipList = tipList;
curTipIndex = 0;
updateTip(STATUS_OUT);
updateTipAndPlayAnimation();
handler.postDelayed(repeatCode, ANIM_DELAYED_MILLIONS);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment