Android聊天軟件開發(fā)(基于網(wǎng)易云IM即時通訊)——添加好友(三)

這里先搭建viewpage+BottomNavigationView+Fragment的底部導(dǎo)航欄

activity_tabhost.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_above="@+id/bnv_viewpager">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="44dp"
            android:background="@color/deepskyblue"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_alignParentStart="true"
                android:gravity="center_vertical">

                <TextView
                    android:id="@+id/tv_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="20dp"
                    android:textColor="@color/white"
                    android:textSize="20sp" />

            </LinearLayout>

            <ImageView
                android:id="@+id/iv_add"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_alignParentEnd="true"
                android:layout_marginTop="12dp"
                android:layout_marginEnd="20dp"
                android:contentDescription="@string/tv_icon"
                android:src="@drawable/add" />

            <ImageView
                android:id="@+id/iv_search"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginTop="12dp"
                android:layout_marginEnd="20dp"
                android:layout_toStartOf="@id/iv_add"
                android:src="@drawable/search" />

        </RelativeLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/vp_viewpager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            />
    </LinearLayout>

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bnv_viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/lightgrey"
        app:itemTextColor="@drawable/color_navigation_selector"
        app:menu="@menu/navigation" />
</RelativeLayout>

fragment_friends.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".friend.FriendsFragment">

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/srl_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_friends"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp" />

    </com.scwang.smartrefresh.layout.SmartRefreshLayout>

</FrameLayout>

fragment_message.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".message.MessageFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

fragment_mine.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".message.MessageFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

ViewPagerFragmentAdapter

package heath.com.chat.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class ViewPagerFragmentAdapter extends FragmentPagerAdapter {

    private Fragment[] fragments;

    public ViewPagerFragmentAdapter(FragmentManager fm, Fragment[] fragments) {
        super(fm);
        this.fragments=fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }

    @Override
    public int getCount() {
        return fragments.length;
    }
}

TabHostActivity

package heath.com.chat;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import heath.com.chat.adapter.ViewPagerFragmentAdapter;
import heath.com.chat.friend.AddFriendsActivity;
import heath.com.chat.friend.FriendsFragment;
import heath.com.chat.message.MessageFragment;
import heath.com.chat.mine.MineFragment;

public class TabHostActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mIvAdd;

    private BottomNavigationView navigationView;
    private ViewPager viewPager;
    private Fragment[] fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabhost);
        //初始化控件
        initView();
        initListener();
        //將各個fragment加入到fragments中
        addFragment();
        //將viewPager和BottomNavigationView的選擇事件連接起來
        link();
        //設(shè)置viewPager的適配器
        ViewPagerFragmentAdapter adapter = new ViewPagerFragmentAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        //設(shè)置初始的頁面項(xiàng)
        navigationView.setSelectedItemId(R.id.navigation_message);
    }

    /**
     * 初始化控件
     */
    private void initView() {

        mIvAdd = this.findViewById(R.id.iv_add);

        navigationView = this.findViewById(R.id.bnv_viewpager);
        viewPager = this.findViewById(R.id.vp_viewpager);
        //將控件默認(rèn)的圖標(biāo)隱藏般堆,以顯示自定義的按鈕圖標(biāo)
        navigationView.setItemIconTintList(null);
    }

    private void initListener() {
        mIvAdd.setOnClickListener(this);
    }

    /**
     * 填充fragments
     */
    private void addFragment() {
        fragments = new Fragment[]{
                new MessageFragment(),
                new FriendsFragment(),
                new MineFragment()
        };
    }

    /**
     * 將viewPager和BottomNavigationView的事件連接起來
     * 分為兩步
     * 1.給viewPager添加監(jiān)聽事件蛹头,即viewPager的頁面變化時,navigation的選中項(xiàng)跟隨變化
     * 2.給navigation添加監(jiān)聽事件谷扣,即當(dāng)navigation的選中項(xiàng)變化時驯遇,viewPager的頁面跟隨變化
     */
    private void link() {
        //給viewPager設(shè)置監(jiān)聽事件,使viewPager頁面變化時BottomNavigationView的item跟隨其變化
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            //以下三個方法是需要重寫的父類方法

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                ////當(dāng)頁面滑動,即當(dāng)前頁面滑動時調(diào)用
            }

            @Override
            public void onPageSelected(int position) {
                //當(dāng)viewpager選定(滑動)后調(diào)用
                switch (position) {
                    case 0:
                        navigationView.setSelectedItemId(R.id.navigation_message);
                        break;
                    case 1:
                        navigationView.setSelectedItemId(R.id.navigation_friends);
                        break;
                    case 2:
                        navigationView.setSelectedItemId(R.id.navigation_mine);
                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //當(dāng)滾動狀態(tài)發(fā)生變化時芹彬,比如從滾動變到不滾動時調(diào)用
            }
        });

        //配置viewPager的頁面隨navigation的選中項(xiàng)變化
        navigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                        //每次點(diǎn)擊后都將所有圖標(biāo)重置到默認(rèn)不選中圖片
                        resetToDefaultIcon();
                        switch (item.getItemId()) {
                            case R.id.navigation_message:
                                viewPager.setCurrentItem(0);
                                //設(shè)置按鈕的圖標(biāo)
                                item.setIcon(R.drawable.select_message);
                                return true;
                            case R.id.navigation_friends:
                                viewPager.setCurrentItem(1);
                                //設(shè)置按鈕的圖標(biāo)
                                item.setIcon(R.drawable.select_friends);
                                return true;
                            case R.id.navigation_mine:
                                viewPager.setCurrentItem(2);
                                //設(shè)置按鈕的圖標(biāo)
                                item.setIcon(R.drawable.select_mine);
                                return true;
                        }

                        return false;
                    }
                });
    }

    /**
     * 重置按鈕的圖片為未選中的圖標(biāo)
     */
    private void resetToDefaultIcon() {
        navigationView.getMenu().findItem(R.id.navigation_message).setIcon(R.drawable.unselect_message);
        navigationView.getMenu().findItem(R.id.navigation_friends).setIcon(R.drawable.unselect_friends);
        navigationView.getMenu().findItem(R.id.navigation_mine).setIcon(R.drawable.unselect_mine);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_add:
                startActivity(new Intent(TabHostActivity.this, AddFriendsActivity.class));
                break;
            default:
                break;
        }
    }
}

FriendsFragment

package heath.com.chat.friend;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.friend.FriendService;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.netease.nimlib.sdk.uinfo.model.UserInfo;

import java.util.HashMap;
import java.util.List;

import heath.com.chat.R;
import heath.com.chat.adapter.FriendAdapter;

public class FriendsFragment extends Fragment {

    private RecyclerView mRvFriends;
    private FriendAdapter friendAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friends, container,
                false);
        initView(view);
        init();
        return view;
    }

    private void initView(View view) {
        mRvFriends = view.findViewById(R.id.rv_friends);
    }

    private void init(){
        List<String> friends = NIMClient.getService(FriendService.class).getFriendAccounts();
        NIMClient.getService(UserService.class).fetchUserInfo(friends)
                .setCallback(new RequestCallback<List<NimUserInfo>>() {
                    @Override
                    public void onSuccess(List<NimUserInfo> param) {
                        if (param.size()>0){
                            friendAdapter = new FriendAdapter(getActivity(), param);
                            mRvFriends.setAdapter(friendAdapter);
                            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                            mRvFriends.setLayoutManager(linearLayoutManager);
                            mRvFriends.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
                            friendAdapter.setOnItemClickListener(new FriendAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    NimUserInfo nimUserInfo = param.get(position);
                                    Intent intent = new Intent(
                                            getActivity(),
                                            FriendInfoActivity.class);
                                    intent.putExtra("nimUserInfo", nimUserInfo);
                                    startActivityForResult(intent, 0);
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                });
    }
}

MessageFragment

package heath.com.chat.message;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import heath.com.chat.R;

public class MessageFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container,
                false);
        return view;
    }
}

MineFragment

package heath.com.chat.mine;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import heath.com.chat.R;

public class MineFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container,
                false);
        return view;
    }
}

在res文件夾下創(chuàng)建一個menu的文件夾,里面放navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/navigation_message"
        android:icon="@drawable/unselect_message"
        android:title="@string/tv_message" />
    <item
        android:id="@+id/navigation_friends"
        android:icon="@drawable/unselect_friends"
        android:title="@string/tv_friend" />
    <item
        android:id="@+id/navigation_mine"
        android:icon="@drawable/unselect_mine"
        android:title="@string/tv_mine" />
</menu>

在drawable創(chuàng)建color_navigation_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/deepskyblue" android:state_checked="true" />
    <item android:color="@color/gainsboro" android:state_checked="false" />
</selector>

這是底部導(dǎo)航欄樣式

image

接下來叉庐,我們開始寫好友搜索

activity_add_friends.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="44dp"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:background="@color/deepskyblue">

            <LinearLayout
                android:id="@+id/ll_return"
                android:layout_width="44sp"
                android:layout_height="44sp"
                android:gravity="center_vertical"
                >

                <ImageView
                    android:layout_width="24sp"
                    android:layout_height="24sp"
                    android:src="@drawable/return1"
                    android:layout_marginStart="20dp"
                    android:contentDescription="@string/tv_icon_des"
                    />

            </LinearLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tv_add_friends"
                android:textColor="@color/white"
                android:textSize="20sp"
                android:layout_marginStart="20dp"
                />

        </LinearLayout>

        <SearchView
            android:id="@+id/sv_search_friends"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:iconifiedByDefault="false"
            android:queryBackground="@null"
            android:submitBackground="@null"
            android:background="@drawable/searchview_line"
            >
        </SearchView>

        <TextView
            android:id="@+id/tv_result"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            />

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_loading"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_gravity="center"
        android:background="@drawable/shape_label_clarity_black">

        <com.github.ybq.android.spinkit.SpinKitView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/pb_loading"
            style="@style/SpinKitView.Large.Circle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            app:SpinKit_Color="@color/white" />

        <TextView
            android:id="@+id/tv_loading_text"
            android:layout_below="@id/pb_loading"
            android:layout_centerHorizontal="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            />

    </RelativeLayout>

</FrameLayout>

AddFriendsActivity

package heath.com.chat.friend;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import heath.com.chat.BaseActivity;
import heath.com.chat.R;
import heath.com.chat.utils.LoadingUtils;

public class AddFriendsActivity extends BaseActivity implements View.OnClickListener {

    private String TAG = "friend";
    private SearchView mSvSearchFriends;
    private LinearLayout mLlReturn;
    private TextView mTvResult;

    private LoadingUtils loadingUtils;

    final ArrayList<Map<String, Object>> listdata = new ArrayList<>();
    private Gson gson;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friends);
        initView();
        init();
        initListener();
    }

    private void initView() {
        mSvSearchFriends = this.findViewById(R.id.sv_search_friends);
        mLlReturn = this.findViewById(R.id.ll_return);
        mTvResult = this.findViewById(R.id.tv_result);
        gson = new Gson();
        loadingUtils = new LoadingUtils(AddFriendsActivity.this, "正在搜索");
    }

    private void init() {
        loadingUtils.creat();
    }

    private void initListener() {
        mLlReturn.setOnClickListener(this);
        mSvSearchFriends.setSubmitButtonEnabled(false);
        mSvSearchFriends.setQueryHint("查找好友");

        mSvSearchFriends.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String account) {
                listdata.clear();
                loadingUtils.show();
                loadFriend(account);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_return:
                finish();
                break;
            default:
                break;
        }
    }

    private void loadFriend(final String account) {
        List<String> accounts = new ArrayList<>();
        accounts.add(account);
        NIMClient.getService(UserService.class).fetchUserInfo(accounts)
                .setCallback(new RequestCallback<List<NimUserInfo>>() {
                    @Override
                    public void onSuccess(List<NimUserInfo> param) {
                        loadingUtils.dismiss();
                        if (param.size() > 0) {
                            Log.i(TAG, "loadFriend: " + param.get(0).getAccount());
                            Intent intent = new Intent(
                                    AddFriendsActivity.this,
                                    FriendInfoActivity.class);
                            intent.putExtra("nimUserInfo", param.get(0));
                            startActivityForResult(intent, 0);
                        } else {
                            mTvResult.setText("未搜索到用戶");
                        }
                    }

                    @Override
                    public void onFailed(int code) {
                        Log.i(TAG, "code: " + code);
                        loadingUtils.dismiss();
                    }

                    @Override
                    public void onException(Throwable exception) {
                        loadingUtils.dismiss();
                    }
                });
    }

}

好友信息展示

activity_friend_info.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/lightgrey"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="44dp"
            android:background="@color/deepskyblue"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <LinearLayout
                android:id="@+id/ll_return"
                android:layout_width="44sp"
                android:layout_height="44sp"
                android:gravity="center_vertical">

                <ImageView
                    android:layout_width="24sp"
                    android:layout_height="24sp"
                    android:layout_marginStart="20dp"
                    android:contentDescription="@string/tv_icon_des"
                    android:src="@drawable/return1" />

            </LinearLayout>

        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_marginTop="20dp"
            android:background="@color/white"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/iv_head_photo"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:contentDescription="@string/tv_icon_des"
                android:src="@drawable/test" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="60dp"
                android:layout_gravity="center_vertical"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="30dp"
                    android:layout_gravity="center_vertical"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/tv_nickname"
                        android:layout_width="wrap_content"
                        android:layout_height="fill_parent"
                        android:gravity="center_vertical"
                        android:textColor="@color/black" />

                    <ImageView
                        android:id="@+id/iv_sex"
                        android:layout_width="16dp"
                        android:layout_height="16dp"
                        android:layout_marginStart="10dp"
                        android:layout_marginEnd="10dp"
                        android:layout_marginTop="7dp"
                        android:contentDescription="@string/tv_icon_des"
                        android:src="@drawable/girl" />

                </LinearLayout>

                <TextView
                    android:id="@+id/tv_address"
                    android:layout_width="wrap_content"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:textColor="@color/grey" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/white"
            android:orientation="horizontal"
            android:layout_marginTop="1dp"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:text="@string/tv_sign"
                android:textColor="@color/black2"
                />

            <TextView
                android:id="@+id/tv_sign"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:text="@string/tv_unfilled"
                android:textColor="@color/grey"
                />

        </LinearLayout>

        <Button
            android:id="@+id/btn_add_friend"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@color/white"
            android:layout_marginTop="10dp"
            android:text="@string/tv_add_friend"
            android:textColor="@color/deepskyblue"
            />

        <Button
            android:id="@+id/btn_send_message"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@color/white"
            android:layout_marginTop="10dp"
            android:text="@string/btn_send_message"
            android:textColor="@color/deepskyblue"
            />

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_loading"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_gravity="center"
        android:background="@drawable/shape_label_clarity_black">

        <com.github.ybq.android.spinkit.SpinKitView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/pb_loading"
            style="@style/SpinKitView.Large.Circle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            app:SpinKit_Color="@color/white" />

        <TextView
            android:id="@+id/tv_loading_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/pb_loading"
            android:layout_centerHorizontal="true"
            android:textColor="@color/white" />

    </RelativeLayout>

</FrameLayout>

FriendInfoActivity

package heath.com.chat.friend;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.friend.FriendService;
import com.netease.nimlib.sdk.friend.constant.VerifyType;
import com.netease.nimlib.sdk.friend.model.AddFriendData;
import com.netease.nimlib.sdk.uinfo.constant.GenderEnum;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import heath.com.chat.BaseActivity;
import heath.com.chat.LoginActivity;
import heath.com.chat.OKhttp.IHttpClient;
import heath.com.chat.OKhttp.IRequest;
import heath.com.chat.OKhttp.IResponse;
import heath.com.chat.OKhttp.impl.OkHttpClientImpl;
import heath.com.chat.OKhttp.impl.RequestImpl;
import heath.com.chat.R;
import heath.com.chat.utils.Common;
import heath.com.chat.utils.LoadingUtils;
import heath.com.chat.utils.ThreadUtils;

public class FriendInfoActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mLlReturn;
    private ImageView mIvHeadPhoto;
    private TextView mTvNickname;
    private ImageView mIvSex;
    private TextView mTvAddress;
    private TextView mTvSign;
    private Button mBtnAddFriend;
    private Button mBtnSendMessage;

    private NimUserInfo nimUserInfo;
    protected LoadingUtils loadingUtils;
    private BaseAnimatorSet mBasIn;
    private BaseAnimatorSet mBasOut;
    private LoginInfo loginInfo;

    private String TAG = "friend";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_info);
        initView();
        initListener();
        init();
    }

    private void initView() {
        mLlReturn = this.findViewById(R.id.ll_return);
        mIvHeadPhoto = this.findViewById(R.id.iv_head_photo);
        mTvNickname = this.findViewById(R.id.tv_nickname);
        mIvSex = this.findViewById(R.id.iv_sex);
        mTvAddress = this.findViewById(R.id.tv_address);
        mTvSign = this.findViewById(R.id.tv_sign);
        mBtnAddFriend = this.findViewById(R.id.btn_add_friend);
        mBtnSendMessage = this.findViewById(R.id.btn_send_message);
    }

    private void initListener() {
        mBtnAddFriend.setOnClickListener(this);
        mBtnSendMessage.setOnClickListener(this);
        mLlReturn.setOnClickListener(this);
    }

    private void init() {
        Intent intent = getIntent();
        nimUserInfo = (NimUserInfo) intent.getSerializableExtra("nimUserInfo");
        loginInfo = (LoginInfo) aCache.getAsObject("loginInfo");
        loadingUtils = new LoadingUtils(FriendInfoActivity.this, "添加好友...");
        mBasIn = new BounceTopEnter();
        mBasOut = new SlideBottomExit();
        loadingUtils.creat();
       if (nimUserInfo.getAccount().equals(loginInfo.getAccount())){
           mBtnAddFriend.setVisibility(View.GONE);
           mBtnSendMessage.setVisibility(View.GONE);
       }else{
           boolean isMyFriend = NIMClient.getService(FriendService.class).isMyFriend(nimUserInfo.getAccount());
           Log.i(TAG, "isMyFriend: "+isMyFriend);
           if (isMyFriend) {
               mBtnAddFriend.setVisibility(View.GONE);
               mBtnSendMessage.setVisibility(View.VISIBLE);
           }else {
               mBtnAddFriend.setVisibility(View.VISIBLE);
               mBtnSendMessage.setVisibility(View.GONE);
           }
       }
        if (nimUserInfo.getName() != null) {
            mTvNickname.setText(nimUserInfo.getName());
        }
        if (nimUserInfo.getSignature() != null) {
            mTvSign.setText(nimUserInfo.getSignature());
        }
        GenderEnum genderEnum = nimUserInfo.getGenderEnum();
        switch (genderEnum) {
            case MALE:
                mIvSex.setImageResource(R.drawable.boy);
                break;
            case FEMALE:
                mIvSex.setImageResource(R.drawable.girl);
                break;
            case UNKNOWN:
                mIvSex.setImageResource(R.drawable.unknown);
                break;
            default:
                mIvSex.setImageResource(R.drawable.unknown);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_add_friend:
                loadingUtils.show();
                addFriend();
                break;
            case R.id.btn_send_message:
                break;
            case R.id.ll_return:
                finish();
                break;
        }
    }

    private void addFriend() {
        final VerifyType verifyType = VerifyType.DIRECT_ADD; // DIRECT_ADD 直接加對方為好友;VERIFY_REQUEST 發(fā)起好友驗(yàn)證請求
        String msg = "好友請求附言";
        NIMClient.getService(FriendService.class).addFriend(new AddFriendData(nimUserInfo.getAccount(), verifyType, msg))
                .setCallback(new RequestCallback<Void>() {
                    @Override
                    public void onSuccess(Void param) {
                        loadingUtils.dismiss();
                        NormalDialogOneBtn("添加好友成功", 200);
                    }

                    @Override
                    public void onFailed(int code) {
                        loadingUtils.dismiss();
                        NormalDialogOneBtn("添加好友失敗", 414);
                    }

                    @Override
                    public void onException(Throwable exception) {
                        loadingUtils.dismiss();
                        NormalDialogOneBtn("添加好友失敗", 500);
                    }
                });
    }

    private void NormalDialogOneBtn(String msg, int code) {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.content(msg)//
                .btnNum(1)
                .btnText("確定")//
                .showAnim(mBasIn)//
                .dismissAnim(mBasOut)//
                .show();

        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
                if (code == 200) {
                    finish();
                }
            }
        });
    }
}

使用aadapter來好友列表顯示

item_friend.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:background="@color/white">

    <ImageView
        android:id="@+id/iv_head_photo"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:contentDescription="@string/tv_icon"
        android:src="@drawable/test"/>

    <TextView
        android:id="@+id/tv_nickname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textColor="@color/black2"
        />

</LinearLayout>

FriendAdapter.java

package heath.com.chat.adapter;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.Collections;
import java.util.List;

import heath.com.chat.R;

public class FriendAdapter extends RecyclerView.Adapter<FriendHolder> {

    private List<NimUserInfo> listdata;
    private Activity context;
    private LayoutInflater mInflater;

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    private OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public FriendAdapter(Activity context, List<NimUserInfo> listdata) {
        this.context = context;
        this.listdata = listdata;
        mInflater = LayoutInflater.from(context);
    }

    @NonNull
    @Override
    public FriendHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View convertView = mInflater.inflate(R.layout.item_friend, viewGroup, false);
        FriendHolder viewHolder = new FriendHolder(convertView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final FriendHolder holder, int position) {
//        if (listdata.get(position).getUserInfo().getIcon() != null && !listdata.get(position).getUserInfo().getIcon().equals("null")) {
//            ImageUitl imageUitl = new ImageUitl(BaseActivity.cache);
//            imageUitl.asyncloadImage(holder.mIvHeadPhoto, Common.HTTP_ADDRESS + Common.USER_FOLDER_PATH + "/" + listdata.get(position).getUserInfo().getIcon());
//        }
        if (listdata.get(position).getName() != null) {
            holder.mTvNickname.setText(listdata.get(position).getName());
        }
        if (mOnItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int layoutPosition = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.itemView, layoutPosition);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return listdata.size();
    }

    public void setData(int position, List<NimUserInfo> list) {
        Collections.reverse(list);
        for (NimUserInfo friendBean : list) {
            listdata.add(position, friendBean);
            notifyItemInserted(position);
        }
    }

}

class FriendHolder extends RecyclerView.ViewHolder {
    ImageView mIvHeadPhoto;
    TextView mTvNickname;

    FriendHolder(@NonNull View itemView) {
        super(itemView);
        mIvHeadPhoto = itemView.findViewById(R.id.iv_head_photo);
        mTvNickname = itemView.findViewById(R.id.tv_nickname);
    }
}

項(xiàng)目下載地址:https://download.csdn.net/download/qq_32090185/11122479

下一章介紹發(fā)送消息(文本)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末舒帮,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子陡叠,更是在濱河造成了極大的恐慌玩郊,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,290評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件匾竿,死亡現(xiàn)場離奇詭異瓦宜,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)岭妖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評論 2 385
  • 文/潘曉璐 我一進(jìn)店門临庇,熙熙樓的掌柜王于貴愁眉苦臉地迎上來反璃,“玉大人,你說我怎么就攤上這事假夺』打冢” “怎么了?”我有些...
    開封第一講書人閱讀 156,872評論 0 347
  • 文/不壞的土叔 我叫張陵已卷,是天一觀的道長梧田。 經(jīng)常有香客問我,道長侧蘸,這世上最難降的妖魔是什么裁眯? 我笑而不...
    開封第一講書人閱讀 56,415評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮讳癌,結(jié)果婚禮上穿稳,老公的妹妹穿的比我還像新娘。我一直安慰自己晌坤,他們只是感情好逢艘,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著骤菠,像睡著了一般它改。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上商乎,一...
    開封第一講書人閱讀 49,784評論 1 290
  • 那天央拖,我揣著相機(jī)與錄音,去河邊找鬼鹉戚。 笑死爬泥,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的崩瓤。 我是一名探鬼主播袍啡,決...
    沈念sama閱讀 38,927評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼却桶!你這毒婦竟也來了境输?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,691評論 0 266
  • 序言:老撾萬榮一對情侶失蹤颖系,失蹤者是張志新(化名)和其女友劉穎嗅剖,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嘁扼,經(jīng)...
    沈念sama閱讀 44,137評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡信粮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評論 2 326
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了趁啸。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片强缘。...
    茶點(diǎn)故事閱讀 38,622評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡督惰,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出旅掂,到底是詐尸還是另有隱情赏胚,我是刑警寧澤,帶...
    沈念sama閱讀 34,289評論 4 329
  • 正文 年R本政府宣布商虐,位于F島的核電站觉阅,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏秘车。R本人自食惡果不足惜典勇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望叮趴。 院中可真熱鬧痴柔,春花似錦、人聲如沸疫向。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽搔驼。三九已至,卻和暖如春侈询,著一層夾襖步出監(jiān)牢的瞬間舌涨,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工扔字, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留囊嘉,地道東北人。 一個月前我還...
    沈念sama閱讀 46,316評論 2 360
  • 正文 我出身青樓革为,卻偏偏與公主長得像扭粱,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子震檩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評論 2 348

推薦閱讀更多精彩內(nèi)容