Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android——今日頭條APP——高仿——ZYFNewsCTZF

Android——今日頭條APP——高仿——ZYFNewsCTZF

編輯:關於Android編程

圖片效果:1

\

\\

\

\

 

主頁代碼:MainActivity:

1.首頁代碼:SyFragment:

1.新聞頻道代碼:

2.新聞內容代碼:

跳轉——顯示新聞詳細內容

適配器——NewsBaseAdapter-NewsFragmentAdapter

entity——MyNews

2.我的代碼:MyFragment:

MyFangment布局

跳轉登錄界面換頭像

RoundImageView 插件

 

 

主頁代碼:MainActivity:FragmentTabHost

 

package com.example.zyfnewsctzf;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.example.zyfnewsctzf.fragment.GzFragment;
import com.example.zyfnewsctzf.fragment.MyFragment;
import com.example.zyfnewsctzf.fragment.SpFragment;
import com.example.zyfnewsctzf.fragment.SyFragment;

public class MainActivity extends AppCompatActivity {
    private FragmentTabHost ft;
    private  String[] str={"首頁","視頻","關注","我的"};
    private  int[] imgRes={R.drawable.sy
            ,R.drawable.sp,R.drawable.gz,R.drawable.my};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initWindow();
        setContentView(R.layout.activity_main);
        ft=(FragmentTabHost)findViewById(R.id.ft);
        getSupportActionBar().hide();
        init();
    }
    //使狀態欄透明的方法
    @TargetApi(19)
    private void initWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);  //狀態欄
          //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//導航欄
        }
    }


    private void init() {
        ft.setup(this, getSupportFragmentManager(), R.id.f1);
        Fragment fragment = new SyFragment();
        TabHost.TabSpec tabSpec0 =
                ft.newTabSpec(str[0]).setIndicator(getView(0));
        ft.addTab(tabSpec0, fragment.getClass(), null);
        Fragment fragment1 = new SpFragment();
        TabHost.TabSpec tabSpec1 =
                ft.newTabSpec(str[1]).setIndicator(getView(1));
        ft.addTab(tabSpec1, fragment1.getClass(), null);
        Fragment fragment2 = new GzFragment();
        TabHost.TabSpec tabSpec2 =
                ft.newTabSpec(str[2]).setIndicator(getView(2));
        ft.addTab(tabSpec2, fragment2.getClass(), null);
        Fragment fragment3 = new MyFragment();
        TabHost.TabSpec tabSpec3 =
                ft.newTabSpec(str[3]).setIndicator(getView(3));
        ft.addTab(tabSpec3, fragment3.getClass(), null);



        }

    public View getView(int i){
        View v=getLayoutInflater().inflate(R.layout.tab_layout,null);
        ImageView iv=(ImageView)v.findViewById(R.id.iv);
        iv.setImageResource(imgRes[i]);
        TextView tv=(TextView)v.findViewById(R.id.tv);
        tv.setText(str[i]);

        return  v;
    }
}


    <framelayout android:id="@+id/f1" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent">
    </framelayout>

    
    


 

1.首頁代碼:SyFragment:

 

<framelayout android:layout_height="match_parent" android:layout_width="match_parent" tools:context="com.example.zyfnewsctzf.fragment.SyFragment" 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">

    
    
    
        


        

        

        

    

</framelayout>

 

1.新聞頻道代碼:

 

package com.example.zyfnewsctzf.fragment;


import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.astuetz.PagerSlidingTabStrip;
import com.example.zyfnewsctzf.R;
import com.example.zyfnewsctzf.adapter.NewsFragmentAdapter;
import com.example.zyfnewsctzf.util.FileUitlity;
import com.example.zyfnewsctzf.util.HttpUtil;
import com.example.zyfnewsctzf.util.UrlUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * A simple {@link Fragment} subclass.
 */
public class SyFragment extends Fragment {
    private PagerSlidingTabStrip pst;
    private ViewPager vp;
    private List fragmentList;
    private List> channelList;
    private List titles;
    private NewsFragmentAdapter nfa;
    public SyFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sy, container, false);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        fragmentList = new ArrayList<>();
        titles  = new ArrayList<>();
        pst = (PagerSlidingTabStrip) getView().findViewById(R.id.pst);
        vp  = (ViewPager) getView().findViewById(R.id.vp);
        nfa = new NewsFragmentAdapter(getChildFragmentManager(), fragmentList, titles);
        vp.setAdapter(nfa);
        vp.setOffscreenPageLimit(2);
        pst.setViewPager(vp);
        pst.setIndicatorHeight(0);
        pst.setUnderlineHeight(0);
        pst.setShouldExpand(true);
        //讀取文件
        String fileName ="channel.txt";
        String pn = getActivity().getPackageName();
        //如果存在頻道文件則讀取 否則 從網絡獲取
        if(FileUitlity.fileExists(pn+"/"+fileName)){
            String ja = FileUitlity.readFileFromSdcard(pn+"/"+fileName);
            try {
                Log.d("=====","讀取文件成功");
                Log.d("====1=",ja);
                initFragment(new JSONArray(ja));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else{
            new GetChannel().execute(UrlUtil.channelUrl);
        }
    }
    public class GetChannel extends AsyncTask {
        @Override
        protected String doInBackground(String... strings) {
            return HttpUtil.HttpGet(strings[0]);
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s==null)
            {
                Toast.makeText(getContext(),"沒有數據網路不好",Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONObject body= jsonObject.getJSONObject("showapi_res_body");
                JSONArray ja = body.getJSONArray("channelList");
                if(ja.length()>0){
                    String pn = getActivity().getPackageName();
                    FileUitlity.getInstance(getActivity(),pn);
                    String result =FileUitlity.saveFileToSdcard(pn+"/channel.txt",
                            ja.toString());
                    if(result.equals("ok")){
                        Log.d("=====","文件保存成功");
                    }else{
                        Log.d("=====","文件保存失敗");
                    }
                }
                initFragment(ja);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    public void initFragment(JSONArray ja) throws JSONException {
        //解析頻道json數據
        channelList = new ArrayList<>();
        for(int i=0;i

 

2.新聞內容代碼:

 

package com.example.zyfnewsctzf.fragment;


import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.example.zyfnewsctzf.R;
import com.example.zyfnewsctzf.adapter.NewsBaseAdapter;
import com.example.zyfnewsctzf.entity.MyNews;
import com.example.zyfnewsctzf.util.HttpUtil;
import com.example.zyfnewsctzf.util.UrlUtil;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsFragment extends Fragment {
    private PullToRefreshListView prlv;
    private NewsBaseAdapter nba;
    private List newsList;
 String  pages,channelId,channelName;
    private String[]  strings;
int  page=1;
    public NewsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_news, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        newsList = new ArrayList<>();
        prlv = (PullToRefreshListView) getView().findViewById(R.id.prlv);
        nba = new NewsBaseAdapter(newsList, getActivity());
        prlv.setAdapter(nba);

        Bundle bundle = getArguments();
        channelId= bundle.getString("id");
        channelName = bundle.getString("name");
        pages= String.valueOf(page);
        strings=new String[]{channelName,channelId,pages};
        new GetNews().execute(strings);




        //上拉下拉
        prlv.setMode(PullToRefreshBase.Mode.BOTH);
        ILoadingLayout upLoading = prlv.getLoadingLayoutProxy(true, false);
        upLoading.setPullLabel("下拉客官請稍等");
        upLoading.setRefreshingLabel("客官刷新中");
        upLoading.setReleaseLabel("好了客官");
        ILoadingLayout downLoading = prlv.getLoadingLayoutProxy(false, true);
        downLoading.setPullLabel("上拉客官請稍等");
        downLoading.setRefreshingLabel("客官刷新中");
        downLoading.setReleaseLabel("好了客官");

        prlv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {
            //下拉
            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
               page=1;
                newsList=new ArrayList();
                pages= String.valueOf(page);
                strings=new  String[]{channelName,channelId,pages};
                new GetNews().execute(strings);
            }
            //上拉
            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                page++;
                newsList=new ArrayList();
                pages= String.valueOf(page);
                strings=new  String[]{channelName,channelId,pages};
                new GetNews().execute(strings);
            }
        });




    }




    public class GetNews extends AsyncTask {
        @Override
        protected String doInBackground(String... strings) {


            String url = UrlUtil.newsUrl + "?channelId=" + strings[1]
                    + "&channelName=" + strings[0]
                    + "&needHtml=1"
                    +"&page="+strings[2]
                    +"&title="+"&needContent"
                    ;


            return HttpUtil.HttpGet(url);
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //解析 新聞數據

            if (s==null)
            {
                Toast.makeText(getContext(),"沒有數據網路不好",Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject obj = new JSONObject(s);
                JSONObject body = obj.getJSONObject("showapi_res_body");
                JSONObject pageBean   = body.getJSONObject("pagebean");
                JSONArray contentList = pageBean.getJSONArray("contentlist");
                for (int i=0;i

<framelayout android:layout_height="match_parent" android:layout_width="match_parent" tools:context="com.example.zyfnewsctzf.fragment.NewsFragment" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

    

    >



</framelayout>
跳轉——顯示新聞詳細內容——ContentActivity

 

 

package com.example.zyfnewsctzf;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.zyfnewsctzf.entity.MyNews;

public class ContentActivity extends AppCompatActivity {
private WebView wv;
    private ImageView back;
    private TextView  title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);
        getSupportActionBar().hide();
        wv=(WebView)findViewById(R.id.wv);
        back=(ImageView)findViewById(R.id.back) ;
        title=(TextView)findViewById(R.id.title) ;
        Intent intent=getIntent();
        String  html="";
        String titles="";
        if (intent!=null){
        MyNews news= intent.getParcelableExtra("news");
            html=news.getHtml();
            titles=news.getTitle();
        }
        title.setText(titles);

        WebSettings ws=wv.getSettings();
        ws.setSupportZoom(true);//支持放大
        ws.setDisplayZoomControls(true);//放大縮小控件  加減號
        ws.setJavaScriptEnabled(true);
        ws.setDefaultTextEncodingName("utf-8");
        wv.setBackgroundColor(getResources().getColor(R.color.backback));
        wv.loadDataWithBaseURL("",html,"text/html","utf-8","");
back.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        finish();
    }
});
    }
}
布局

 

 




    
   

    





 

適配器——NewsBaseAdapter-NewsFragmentAdapter

 

package com.example.zyfnewsctzf.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.zyfnewsctzf.ContentActivity;
import com.example.zyfnewsctzf.R;
import com.example.zyfnewsctzf.entity.MyNews;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * Created by 沖天之峰 on 2016/8/18.
 */
public class NewsBaseAdapter extends BaseAdapter{
    private List myNews;
    private Context context;
    private final int  TYPE1=0,TYPE2=1,TYPE3=2,TYPE4=3,TYPE5=4;

    public NewsBaseAdapter( List myNews,Context context) {
        this.context = context;
        this.myNews = myNews;
    }

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

    @Override
    public Object getItem(int i) {
        return myNews.get(i);
    }

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

    @Override
    public int getItemViewType(int position) {
        switch (paserImageList(myNews.get(position).getImageurls()).size()){
            case 0:return TYPE1;
            case 1:return TYPE2;
            case 2:return TYPE3;
            case 3:return TYPE4;
            case 4:return TYPE5;
        }
        return 0;
    }

    @Override
    public int getViewTypeCount() {
        return 5;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder vh;
        int type = getItemViewType(i);
        if(view == null){
            vh = new ViewHolder();
            if(type ==0){
                view = LayoutInflater.from(context).inflate(R.layout.list_layout_base1,null);
                vh.title = (TextView) view.findViewById(R.id.title);
                vh.content = (TextView) view.findViewById(R.id.content);
                vh.pubDate = (TextView) view.findViewById(R.id.pubDate);
                vh.from = (TextView) view.findViewById(R.id.from);
                view.setTag(vh);
            }else if (type ==1){
                view = LayoutInflater.from(context).inflate(R.layout.list_layout_base2,null);
                vh.title = (TextView) view.findViewById(R.id.title);
                vh.content = (TextView) view.findViewById(R.id.content);
                vh.pubDate = (TextView) view.findViewById(R.id.pubDate);
                vh.from = (TextView) view.findViewById(R.id.from);
                vh.ii = (TextView) view.findViewById(R.id.ii);

                vh.img = (ImageView) view.findViewById(R.id.img);
                view.setTag(vh);
            }else if (type ==2) {
                view = LayoutInflater.from(context).inflate(R.layout.list_layout_base3,null);
                vh.title = (TextView) view.findViewById(R.id.title);
                vh.content = (TextView) view.findViewById(R.id.content);
                vh.pubDate = (TextView) view.findViewById(R.id.pubDate);
                vh.from = (TextView) view.findViewById(R.id.from);

                vh.img1 = (ImageView) view.findViewById(R.id.img1);
                vh.img2 = (ImageView) view.findViewById(R.id.img2);
                view.setTag(vh);
            }
            else if (type ==3) {
                view = LayoutInflater.from(context).inflate(R.layout.list_layout_base4,null);
                vh.title = (TextView) view.findViewById(R.id.title);
                vh.content = (TextView) view.findViewById(R.id.content);
                vh.pubDate = (TextView) view.findViewById(R.id.pubDate);
                vh.from = (TextView) view.findViewById(R.id.from);
                vh.ii = (TextView) view.findViewById(R.id.ii);
                vh.img31 = (ImageView) view.findViewById(R.id.img31);
                vh.img32 = (ImageView) view.findViewById(R.id.img32);
                vh.img33 = (ImageView) view.findViewById(R.id.img33);
                view.setTag(vh);
            }
            else if (type ==4) {
                view = LayoutInflater.from(context).inflate(R.layout.list_layout_base5,null);
                vh.title = (TextView) view.findViewById(R.id.title);
                vh.content = (TextView) view.findViewById(R.id.content);
                vh.pubDate = (TextView) view.findViewById(R.id.pubDate);
                vh.from = (TextView) view.findViewById(R.id.from);

                vh.img41 = (ImageView) view.findViewById(R.id.img41);
                vh.img42 = (ImageView) view.findViewById(R.id.img42);

                vh.img43 = (ImageView) view.findViewById(R.id.img43);
                vh.img44 = (ImageView) view.findViewById(R.id.img44);
                view.setTag(vh);
            }


        }else{
            vh = (ViewHolder) view.getTag();
        }
        MyNews news = myNews.get(i);
        if(type == 0){
            vh.title.setText(news.getTitle());
            vh.content.setText(news.getHtml());
            vh.pubDate.setText(news.getPubDate());
            vh.from.setText(news.getSource());
        }else if (type == 1){
            vh.title.setText(news.getTitle());
            vh.content.setText(news.getHtml());
            vh.pubDate.setText(news.getPubDate());
            vh.from.setText(news.getSource());
            vh.ii.setText(news.getImageurls());
            List list=paserImageList(news.getImageurls());
            if(list.size()==1){
                Glide.with(context).load(list.get(0)).into(vh.img);
            }


        }else if (type == 2){
            vh.title.setText(news.getTitle());
            vh.content.setText(news.getHtml());
            vh.pubDate.setText(news.getPubDate());
            vh.from.setText(news.getSource());
            List list=paserImageList(news.getImageurls());
            if(list.size()==2){
                Glide.with(context).load(list.get(0)).into(vh.img1);
                Glide.with(context).load(list.get(1)).into(vh.img2);
            }
        }
        else if (type == 3){
            vh.title.setText(news.getTitle());
            vh.content.setText(news.getHtml());
            vh.pubDate.setText(news.getPubDate());
            vh.from.setText(news.getSource());
            vh.ii.setText(news.getImageurls());
            List list=paserImageList(news.getImageurls());

            if(list.size()==3){
                Glide.with(context).load(list.get(0)).into(vh.img31);
                Glide.with(context).load(list.get(1)).into(vh.img32);
                Glide.with(context).load(list.get(2)).into(vh.img33);
            }
        } else if (type == 4){
            vh.title.setText(news.getTitle());
            vh.content.setText(news.getHtml());
            vh.pubDate.setText(news.getPubDate());
            vh.from.setText(news.getSource());

            List list=paserImageList(news.getImageurls());

            if(list.size()==4){
                Glide.with(context).load(list.get(0)).into(vh.img41);
                Glide.with(context).load(list.get(1)).into(vh.img42);
                Glide.with(context).load(list.get(2)).into(vh.img43);
                Glide.with(context).load(list.get(3)).into(vh.img44);
            }
        }

        view.setOnClickListener(new ClickLisner(i));
            return view;
    }
    public class ClickLisner implements View.OnClickListener {
        private int position;

        //在類裡生成構造 把position傳進來
        public ClickLisner(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            MyNews news = myNews.get(position);
         Log.d("======", news.getHtml());
            Intent intent=new Intent(context, ContentActivity.class);
            //MyNews要實現序列化
            intent.putExtra("news",news);
            context.startActivity(intent);
        }
    }

    //此處的控件變量是為了關聯布局中的控件,以便傳值。
    private class ViewHolder{
        //布局1中使用的控件
        TextView title;
        TextView content;
        TextView pubDate;
        TextView ii;
        TextView from;
        ImageView img;
        ImageView img1;
        ImageView img2;
        ImageView img31;
        ImageView img32;
        ImageView img33;
        ImageView img41;
        ImageView img42;
        ImageView img43;
        ImageView img44;
    }




    public List paserImageList (String imgList){
        List img=new ArrayList();
        try {
            JSONArray jsonArray = new JSONArray(imgList);
            for(int i = 0;i
package com.example.zyfnewsctzf.adapter;

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

import java.util.List;

/**
 * Created by 沖天之峰 on 2016/8/18.
 */
public class NewsFragmentAdapter extends FragmentPagerAdapter {

    private List fragmentList;
   private List  titles;

    public NewsFragmentAdapter(FragmentManager fm, List fragmentList, List titles) {
        super(fm);
        this.fragmentList = fragmentList;
        this.titles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);

    }

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

    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
}

 

entity——MyNews

 

package com.example.zyfnewsctzf.entity;

import android.os.Parcel;
import android.os.Parcelable;

import java.util.List;

/**
 * Created by Administrator on 2016/8/18.
 */
public class MyNews implements Parcelable{
    private String pubDate;
    private String title;
    private String channelName;
    private String desc;
    private String source;
    private String channelId;
    private String link;
    private String html;
    private List allList;
    private String imageurls;

    public MyNews() {
    }

    protected MyNews(Parcel in) {
        pubDate = in.readString();
        title = in.readString();
        channelName = in.readString();
        desc = in.readString();
        source = in.readString();
        channelId = in.readString();
        link = in.readString();
        html = in.readString();
        allList = in.createStringArrayList();
        imageurls = in.readString();
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public MyNews createFromParcel(Parcel in) {
            return new MyNews(in);
        }

        @Override
        public MyNews[] newArray(int size) {
            return new MyNews[size];
        }
    };

    public String getPubDate() {
        return pubDate;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getChannelName() {
        return channelName;
    }

    public void setChannelName(String channelName) {
        this.channelName = channelName;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getChannelId() {
        return channelId;
    }

    public void setChannelId(String channelId) {
        this.channelId = channelId;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getHtml() {
        return html;
    }

    public void setHtml(String html) {
        this.html = html;
    }

    public List getAllList() {
        return allList;
    }

    public void setAllList(List allList) {
        this.allList = allList;
    }

    public String getImageurls() {
        return imageurls;
    }

    public void setImageurls(String imageurls) {
        this.imageurls = imageurls;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(pubDate);
        parcel.writeString(title);
        parcel.writeString(channelName);
        parcel.writeString(desc);
        parcel.writeString(source);
        parcel.writeString(channelId);
        parcel.writeString(link);
        parcel.writeString(html);
        parcel.writeStringList(allList);
        parcel.writeString(imageurls);
    }
}

 

2.我的代碼:MyFragment:

 

package com.example.zyfnewsctzf.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.zyfnewsctzf.MyIntentActivity;
import com.example.zyfnewsctzf.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyFragment extends Fragment {
private ImageView login;

    public MyFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my, container, false);

    }




    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        login=(ImageView)getView().findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent= new Intent(getActivity(),MyIntentActivity.class);
                getActivity().startActivity(intent);
            }
        });

    }
}
MyFangment布局


    
    
        


        

            

                

                    

                

                

跳轉登錄界面換頭像

 

 

package com.example.zyfnewsctzf;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.example.zyfnewsctzf.util.FileUitlity1;
import com.example.zyfnewsctzf.util.RoundImageView;

import java.io.File;

public class MyIntentActivity  extends AppCompatActivity implements View.OnClickListener {
    private PopupWindow pw;
    private View popView;
    private RoundImageView riv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent);
      getSupportActionBar().hide();
        //加載PopWindow中的布局
        popView = getLayoutInflater().inflate(R.layout.pop_layout, null);
        //從主布局中取得控件

        //從PopWindow布局中取得控件
        Button xc = (Button)popView.findViewById(R.id.xc);
        Button xj = (Button)popView.findViewById(R.id.xj);
        Button bt = (Button)popView.findViewById(R.id.bt);

        riv = (RoundImageView) findViewById(R.id.riv);
        //注冊   本類監聽

        riv.setOnClickListener(this);
        xc.setOnClickListener(this);
        xj.setOnClickListener(this);
        bt.setOnClickListener(this);
        //顯示Intent,明確指定要跳轉的組件
//        Intent intent=new Intent(IntentActivity.this,SecondActivity.class);
//        startActivity(intent);

        //---------------------------------------


    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {

            case R.id.riv://點擊頭像打開PopWindow
                pw=getPopWindow(popView);
                break;
            case R.id.xc:
                phonePhoto();
                break;
            case R.id.xj:
                takephoto();
                break;
            case R.id.bt:
                pw.dismiss();
                break;
        }
    }



    /*
    * 調用圖庫
    * */
    public void phonePhoto(){
        Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent,2);

    }

    /*
    * 調用相機
    * */
    private String capturePath="";
    public void takephoto(){
        Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File parent= FileUitlity1.getInstance(getApplicationContext())
                .makeDir("head_imag");
        capturePath=parent.getPath()+File.separatorChar+System.currentTimeMillis()+".jpg";
        camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(capturePath)));
        camera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
        startActivityForResult(camera, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode!= Activity.RESULT_OK){

            return;
        }
        //相機返回結果,調用系統裁剪啊
        if (requestCode==1){
            startPicZoom(Uri.fromFile(new File(capturePath)));

        }
        //相冊返回結果調用系統裁剪
        else if (requestCode==2){
            Cursor cursor=getContentResolver()
                    .query(data.getData(),new String[]{MediaStore.Images.Media.DATA}
                            ,null,null,null);
            cursor.moveToFirst();
            String  capturePath=cursor.getString(
                    cursor.getColumnIndex(
                            MediaStore.Images.Media.DATA));
            cursor.close();
            startPicZoom(Uri.fromFile(new File(capturePath)));
        }
        else if (requestCode==3){
            Bundle bundle= data.getExtras();
            if (bundle!=null){
                Bitmap bitmap=bundle.getParcelable("data");
                riv.setImageBitmap(bitmap);

            }
        }
    }

    /*
    調用系統裁剪功能

     */
    public  void  startPicZoom(Uri  uri){
        Intent intent=new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");
        intent.putExtra("crop","true");//允許裁剪
        intent.putExtra("aspectX",1);//設置裁剪比例
        intent.putExtra("aspectY",1);
        //設置圖片寬度高度
        intent.putExtra("outputX",150);
        intent.putExtra("outputY",150);
        intent.putExtra("return-data",true);
        startActivityForResult(intent,3);

    }



    //設置屏幕背景透明度方法
    public void backgroundAlpha(float bgAlpha){
        WindowManager.LayoutParams ll=getWindow().getAttributes();
        ll.alpha=bgAlpha;
        getWindow().setAttributes(ll);
    }
    //構建一個PopWindow
    public PopupWindow getPopWindow(View view){
        PopupWindow popupWindow=new PopupWindow(view,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,true);
        // popupWindow.setFocusable(true);
        //點擊pop外面是否消失
        popupWindow.setOutsideTouchable(true);

        popupWindow.setAnimationStyle(R.style.popStyle);
        //設置背景透明度
        backgroundAlpha(0.3f);
        //————————
        //設置View隱藏
        riv.setVisibility(View.GONE);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.showAtLocation(riv, Gravity.BOTTOM, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //設置背景透明度
                backgroundAlpha(1f);
                //設置View可見
                riv.setVisibility(View.VISIBLE);
            }
        });
        return popupWindow;
    }

}

 

布局1+2

 





    
    
    

2pop

 

 


 

RoundImageView 插件

package com.example.zyfnewsctzf.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundImageView extends ImageView {
	public RoundImageView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public RoundImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onDraw(Canvas canvas) {

		Drawable drawable = getDrawable();

		if (drawable == null) {
			return;
		}

		if (getWidth() == 0 || getHeight() == 0) {
			return;
		}

		Bitmap b = null;
		if(drawable instanceof BitmapDrawable){
			b = ((BitmapDrawable) drawable).getBitmap();
		}else if(drawable instanceof Drawable){
			b = Bitmap.createBitmap(   
		                getWidth(),   
		                getHeight(),   
		                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
		                : Bitmap.Config.RGB_565);
		                Canvas canvas1 = new Canvas(b);   
		                // canvas.setBitmap(bitmap);   
		                drawable.setBounds(0, 0, getWidth(),   
		                getHeight());   
		                drawable.draw(canvas1);  
		}

		if (null == b) {
			return;
		}

		Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
		int w = getWidth(), h = getHeight();

		Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
		canvas.drawBitmap(roundBitmap, 0, 0, null);

	}

	public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
		Bitmap sbmp;
		if (bmp.getWidth() != radius || bmp.getHeight() != radius)
			sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
		else
			sbmp = bmp;
		Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(),
				Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xffa19774;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(Color.parseColor("#BAB399"));
		canvas.drawCircle(sbmp.getWidth() / 2 + 0.7f,
				sbmp.getHeight() / 2 + 0.7f, sbmp.getWidth() / 2 + 0.1f, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(sbmp, rect, rect, paint);
		return output;
	}
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved