侧拉菜单+上拉加载下拉刷新 显示详细信息

//侧拉布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    <me.maxwin.view.XListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <fragment
        class="com.bawei.fragment.NaviFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"/>

</android.support.v4.widget.DrawerLayout>

//主页面

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawer_layout;
    private ActionBarDrawerToggle mToggle;
    private XListView list_view;
    private ArrayList<News.ResultBean> list;
    private NewsAdpater newsAdpater;
    private int page=1;
    private boolean isLoadMore=false;
    public static final String NEWS_URL="http://172.17.8.100/movieApi/movie/v1/findReleaseMovieList?count=10&page=";
    private Handler handler = new Handler(){};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        drawer_layout = findViewById(R.id.drawer_layout);
        list_view = findViewById(R.id.list_view);
        //初始化ActionBar
        intiActionBar();
        //创建集合
        list = new ArrayList<>();
        //创建适配器
        newsAdpater = new NewsAdpater(list, MainActivity.this);
        list_view.setAdapter(newsAdpater);
        getNews();
        //设置上拉加载下拉刷新
        list_view.setPullLoadEnable(true);
        list_view.setPullRefreshEnable(true);
        //设置Xlistview监听事件
        list_view.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                if (page>1){
                    page--;
                }else {
                    Toast.makeText(MainActivity.this,"给不了亲更多信息了!!!",Toast.LENGTH_LONG).show();
                }
                isLoadMore=false;
                getNews();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        list_view.stopRefresh();
                    }
                },1000);
                long l = System.currentTimeMillis();
                Date date = new Date(l);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                list_view.setRefreshTime(format.format(date));
            }

            @Override
            public void onLoadMore() {
                page ++;
                isLoadMore = true;
                getNews();
                News news = new News();
                ArrayList<News.ResultBean> result = (ArrayList<News.ResultBean>) news.getResult();
                if (result == null){
                    Toast.makeText(MainActivity.this,"没有更多的数据了",Toast.LENGTH_SHORT).show();
                }
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        list_view.stopLoadMore();
                    }
                },1000);
            }
        });
        list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                intent.putExtra("id",newsAdpater.getItem(position).getId()+"");
                startActivity(intent);
            }
        });
    }

    private void getNews() {
        new AsyncTask<String,Integer,String>(){
            @Override
            protected String doInBackground(String... strings) {
                return HttpUtil.getHttpUrlConnection(strings[0]);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Gson gson = new Gson();
                News news = gson.fromJson(s, News.class);
                if (news != null){
                    ArrayList<News.ResultBean> result = (ArrayList<News.ResultBean>) news.getResult();
                    if (result != null){
                        if (!isLoadMore){
                            list.clear();
                        }
                        list.addAll(result);
                        newsAdpater.notifyDataSetChanged();
                    }
                }
            }
        }.execute(NEWS_URL+page);
    }

    //设置我点击左上角,能够弹出侧边菜单
    private void intiActionBar() {
        //获取一个ActionBar对象
        ActionBar actionBar = getSupportActionBar();
        //给左上角一张图片,4.0意思默认图片,给true就可以直接使用
        actionBar.setDisplayHomeAsUpEnabled(true);
        //有一类提供了绑定DrawerLayout功能
        mToggle = new ActionBarDrawerToggle(this, drawer_layout, R.string.open, R.string.close);
        //DrawerLayout和ActionBar关联
        mToggle.syncState();//同步状态
        drawer_layout.addDrawerListener(mToggle);
        drawer_layout.setScrimColor(Color.TRANSPARENT);
    }
    //A.设置左上角按钮具备点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

//详细信息页面和布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/details"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/image_view"
            android:layout_width="180dp"
            android:layout_height="252dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/name_text"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/name_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:textColor="#000"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toTopOf="@id/summary_text"
            app:layout_constraintLeft_toRightOf="@id/image_view"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/summary_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:lineSpacingExtra="2dp"
            android:maxLines="3"
            android:padding="10dp"
            app:layout_constraintBottom_toTopOf="@id/placeOrigin_text"
            app:layout_constraintLeft_toRightOf="@id/image_view"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/name_text" />

        <TextView
            android:id="@+id/country"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:padding="10dp"
            android:text="国家"
            app:layout_constraintBaseline_toBaselineOf="@id/placeOrigin_text"
            app:layout_constraintLeft_toRightOf="@id/image_view"
            app:layout_constraintRight_toLeftOf="@id/placeOrigin_text" />

        <TextView
            android:id="@+id/placeOrigin_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            app:layout_constraintBottom_toTopOf="@id/duration_text"
            app:layout_constraintLeft_toRightOf="@id/country"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/summary_text" />

        <TextView
            android:id="@+id/duration_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="10dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toRightOf="@id/image_view"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/placeOrigin_text" />

    </android.support.constraint.ConstraintLayout>

    <android.support.constraint.ConstraintLayout
        android:id="@+id/performers"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="50dp"
        android:background="#999"
        android:padding="10dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/details">

        <TextView
            android:id="@+id/director"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="导演:"
            app:layout_constraintBaseline_toBaselineOf="@id/director_text" />

        <TextView
            android:id="@+id/director_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="10dp"
            app:layout_constraintLeft_toRightOf="@id/director"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/performer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="演员:"
            app:layout_constraintBaseline_toBaselineOf="@id/starring_text" />

        <TextView
            android:id="@+id/starring_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="10dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toRightOf="@id/performer"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/director_text" />
    </android.support.constraint.ConstraintLayout>

    <TextView
        android:id="@+id/summary"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:lineSpacingExtra="2dp"
        android:padding="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/performers" />

</android.support.constraint.ConstraintLayout>
public class ShowActivity extends AppCompatActivity {
    private ImageView imageView;
    private TextView nameText;
    private TextView summaryText;
    private TextView placeOriginText;
    private TextView durationText;
    private TextView directorText;
    private TextView starringText;
    private TextView summary;
    private String urlString;
    private String id;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Movie movie=(Movie) msg.obj;
            if (movie==null){
                Toast.makeText(ShowActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
            }else {
                switch (msg.what) {
                    case 0:
                        //设置值
                        Movie.ResultBean result = movie.getResult();
                        ImageLoader.getInstance().displayImage(result.getImageUrl(), imageView);
                        nameText.setText(result.getName());
                        summaryText.setText(result.getSummary());
                        placeOriginText.setText(result.getPlaceOrigin());
                        durationText.setText(result.getDuration());
                        directorText.setText(result.getDirector());
                        starringText.setText(result.getStarring());
                        //首行缩进两个字符
                        summary.setText("\u3000\u3000" + result.getSummary());
                        break;
                }
            }
            return true;
        }
    }){

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        //找控件
        imageView = findViewById(R.id.image_view);
        nameText = findViewById(R.id.name_text);
        summaryText = findViewById(R.id.summary_text);
        placeOriginText = findViewById(R.id.placeOrigin_text);
        durationText = findViewById(R.id.duration_text);
        directorText = findViewById(R.id.director_text);
        starringText = findViewById(R.id.starring_text);
        summary = findViewById(R.id.summary);
        //得到之前的id
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        urlString = "http://172.17.8.100/movieApi/movie/v1/findMoviesById?movieId="+id;
        getMovie();
    }

    private void getMovie() {
        //开启一个子线程进行网络耗时操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用封装的HttpUrlConnectionUtil的get请求方法
                String httpUrlConnection = HttpUtil.getHttpUrlConnection(urlString);
                //判断是否访问成功
                if (httpUrlConnection.isEmpty()) {
                    handler.sendMessage(handler.obtainMessage(0));
                } else {
                    //Gson解析JSON对象
                    Movie movie = new Gson().fromJson(httpUrlConnection, Movie.class);
                    handler.sendMessage(handler.obtainMessage(0, movie));
                }
            }
        }).start();
    }
}

//ImageLoader

public class BaseApplication extends Application {
    private File file;
    private DiskCache diskCache;

    @Override
    public void onCreate() {
        super.onCreate();

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File rootSD = Environment.getExternalStorageDirectory();
            file = new File(rootSD, "imagefile");
            if (!file.exists()){
                file.mkdirs();
            }
        }

        try {
            diskCache = new LruDiskCache(file, new Md5FileNameGenerator(), 50 * 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
        BitmapDisplayer displayer = new RoundedBitmapDisplayer(10);

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.ARGB_4444)
                .displayer(displayer)
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .showImageOnLoading(R.mipmap.ic_launcher)
                .build();

        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
                .diskCache(diskCache)
                .memoryCache(new LruMemoryCache(12*1024*1024))
                .threadPoolSize(3)
                .defaultDisplayImageOptions(options)
                .build();

        ImageLoader.getInstance().init(configuration);
    }
}

//适配器

public class NewsAdpater extends BaseAdapter {
    private ArrayList<News.ResultBean> list;
    private Context context;

    public NewsAdpater(ArrayList<News.ResultBean> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public News.ResultBean getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView==null){
            convertView = View.inflate(context, R.layout.list_item, null);
            holder=new ViewHolder();
            holder.imageView=convertView.findViewById(R.id.img_view);
            holder.title=convertView.findViewById(R.id.text_title);
            holder.content=convertView.findViewById(R.id.text_content);
            convertView.setTag(holder);
        }else {
            holder=(ViewHolder) convertView.getTag();
        }
        holder.title.setText(list.get(position).getName());
        holder.content.setText(list.get(position).getSummary());
        ImageLoader.getInstance().displayImage(list.get(position).getImageUrl(),holder.imageView);
        return convertView;
    }
    class ViewHolder{
         ImageView imageView;
         TextView title;
         TextView content;
    }
}

//Http工具类

public class HttpUtil {
    public static String getHttpUrlConnection(String urlString){
        String result = "";
        try {
            URL url = new URL(urlString);
            //连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //优化
            //请求类型
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(false);
            connection.setUseCaches(false);
            //超时时间
            connection.setConnectTimeout(3000);
            connection.connect();

            //获取状态码   200 成功
            if(connection.getResponseCode() == 200){
                InputStream is = connection.getInputStream();
                result = getInputStream(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String getInputStream(InputStream is) {
        String result = "";
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int count = -1;
            byte[] buffer = new byte[1024];
            while ((count = is.read(buffer,0,buffer.length)) != -1){
                baos.write(buffer,0,count);
                baos.flush();
            }
            result = baos.toString();
            baos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/Mr_Cao_/article/details/83375059