ViewPager和Fragment的结合

来源:互联网 发布:网络研修教学反思 编辑:程序博客网 时间:2024/05/17 03:27

直接上代码,注意:本demo用第三方pullToReflesh和sharedSDK第三方登陆和分享,需要自己添加。



import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;
import java.util.HashMap;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class OwhatActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {
    private RadioButton first;
    private RadioButton message;
    private RadioButton task;
    private RadioButton milestone;
    private RadioButton mine;
    private FragmentTransaction fragmentTransaction;
    private Fragment FirstFragment;
    private Fragment MessageFragment;
    private Fragment MilestoneFragment;
    private Fragment MineFragment;
    private long time;
    private FragmentTransaction fragmentTransaction1;
    private Button share;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_owhat);
        initView();
        initFragment();
        check();
        /*
        * 碎片管理器对象
        * */
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.container, FirstFragment).commit();
        task.setOnClickListener(this);
        mine.setOnClickListener(this);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
                //第三方登录
//                ShareSDK.initSDK(OwhatActivity.this);
//                Platform platform = ShareSDK.getPlatform(OwhatActivity.this, "QQ.NAME");
//                platform.setPlatformActionListener(new PlatformActionListener() {
//                    @Override
//                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                        PlatformDb db = platform.getDb();
//                        String token = db.getToken();
//                        Log.i("TAG",db.getUserIcon());
//                        Log.i("TAG",db.getPlatformNname());
//                        Log.i("TAG",hashMap.toString());
//                    }
//
//                    @Override
//                    public void onError(Platform platform, int i, Throwable throwable) {
//                        Toast.makeText(OwhatActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
//                    }
//
//                    @Override
//                    public void onCancel(Platform platform, int i) {
//                        Toast.makeText(OwhatActivity.this,"授权取消",Toast.LENGTH_SHORT).show();
//
//                    }
//                });
            }
        });
    }
    private void initFragment() {
        FirstFragment = fragment.FirstFragment.newInstance();
        MessageFragment = fragment.MessageFragment.newInstance();
        MilestoneFragment = fragment.MilestoneFragment.newInstance();
    }
    /*
    * radioButton的监听事件
    * */
    private void check() {
        first.setOnCheckedChangeListener(this);
        message.setOnCheckedChangeListener(this);
        milestone.setOnCheckedChangeListener(this);
        mine.setOnCheckedChangeListener(this);
    }
    /**
     * 初始化控件
     * */
    private void initView() {
        first = ((RadioButton) findViewById(R.id.bottom_first));
        message = ((RadioButton) findViewById(R.id.bottom_message));
        task = ((RadioButton) findViewById(R.id.bottom_task));
        milestone = ((RadioButton) findViewById(R.id.bottom_milestone));
        mine = ((RadioButton) findViewById(R.id.bottom_mine));
        share = ((Button) findViewById(R.id.textShare));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_owhat, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();


        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    /*
    * radiobutton被选择的点击事件
    * */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
        switch (buttonView.getId()){
            case R.id.bottom_first:
                if (!FirstFragment.isAdded()){
                    fragmentTransaction1.replace(R.id.container, FirstFragment);
                }else{
                    fragmentTransaction1.show(FirstFragment);
                }
                fragmentTransaction1.commit();
                break;
            case R.id.bottom_message:
                if (!MessageFragment.isAdded()){
                    fragmentTransaction1.replace(R.id.container, MessageFragment);
                }else{
                    fragmentTransaction1.show(MessageFragment);
                }
                fragmentTransaction1.commit();
                break;
            case R.id.bottom_milestone:
                if (!MilestoneFragment.isAdded()){
                    fragmentTransaction1.replace(R.id.container, MilestoneFragment);
                }else{
                    fragmentTransaction1.show(MilestoneFragment);
                }
                fragmentTransaction1.commit();
                break;
        }


    }
    /*
    * 系统退出按钮的返回点击监听事件
    * */
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        //Data data=new Data();
        if(keyCode== KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_UP){
            if(System.currentTimeMillis()-time>2000){
                Toast.makeText(this, "再点击一次退出程序", Toast.LENGTH_SHORT).show();
                time=System.currentTimeMillis();
            }
            else{
                System.exit(0);
            }
        }
        return true;
    }
    /*
    * task和mine的点击监听事件
    * */
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.bottom_task:
                Toast.makeText(OwhatActivity.this,"发任务",Toast.LENGTH_SHORT).show();
                break;
            case R.id.bottom_mine:
                Toast.makeText(OwhatActivity.this,"我的",Toast.LENGTH_SHORT).show();
                break;
        }


    }
    /*
    * 第三方分享
    * */
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();


// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(getString(R.string.share));
        // titleUrl是标题的网络链接,仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本,所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信(包括好友和朋友圈)中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论,仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称,仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址,仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");


// 启动分享GUI
        oks.show(this);
    }
}




FirstFragment 代码:
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import cn.owhat.com.owhat.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class FirstFragment extends Fragment implements RadioGroup.OnCheckedChangeListener {


    private RadioButton discover;
    private RadioButton help;
    private RadioButton focus;
    private RadioGroup group;


    public static Fragment newInstance(){
        return new FirstFragment();
    }
    public FirstFragment() {
        // Required empty public constructor
    }




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = (View) inflater.inflate(R.layout.fragment_first, null);
        initView(view);
        group.setOnCheckedChangeListener(this);
        return view;
    }


    private void initView(View view) {
        group = ((RadioGroup) view.findViewById(R.id.group));
        discover = (RadioButton) view.findViewById(R.id.discover);
        help = ((RadioButton) view.findViewById(R.id.help));
        focus = ((RadioButton) view.findViewById(R.id.focus));
    }




    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch(group.getId()){
            case R.id.focus:
                focus.setTextColor(Color.WHITE);
                break;
            case R.id.discover:
                discover.setTextColor(Color.WHITE);
                break;
            case R.id.help:
                help.setTextColor(Color.WHITE);
                break;
        }
    }
}






MessageFragment 代码:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.util.List;
import cn.owhat.com.owhat.R;


/**
 * A simple {@link Fragment} subclass.
 */
public class MessageFragment extends Fragment {
    //上拉加载 下拉刷新
    private PullToRefreshListView pullToReflesh;
    private String[] demo={"O!每电台","任务通知","订单信息"};
    private ILoadingLayout startLabels;


    public static Fragment newInstance(){
        return new MessageFragment();
    }
    public MessageFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_message, null);
        pullToReflesh = ((PullToRefreshListView) view.findViewById(R.id.pull_refresh_list));
        ArrayAdapter adapter=new ArrayAdapter(getActivity(),android.R.layout.simple_expandable_list_item_1,demo);
        pullToReflesh.setAdapter(adapter);
        startLabels  = pullToReflesh.getLoadingLayoutProxy();
        startLabels.setPullLabel("屌丝,下拉加载......");
        startLabels.setRefreshingLabel("正在刷新......");
//        startLabels.setReleaseLabel("成功了哦!");
        pullToReflesh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
               /*
               * 设置时间
               * */
                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                startLabels.setLastUpdatedLabel(label);
                 /*
                * 写下拉刷新的异步任务
                * */
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                /*
                * 写上拉加载的异步任务
                * */
            }
        });
        return view;
    }
    class MessageAdapter extends BaseAdapter{


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


        @Override
        public Object getItem(int position) {
            return null;
        }


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


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return null;
        }
    }


}


MilestoneFragment 代码:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import cn.owhat.com.owhat.R;


/**
 * A simple {@link Fragment} subclass.
 */
public class MilestoneFragment extends Fragment {


    public static Fragment newInstance(){
        return new MilestoneFragment();
    }
    public MilestoneFragment() {
        // 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_milestone, container, false);
    }
}



activity_owhat  xml布局文件代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="cn.owhat.com.owhat.OwhatActivity">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="10"
        android:id="@+id/container">
    </LinearLayout>
    <Button
        android:id="@+id/textShare"
        android:text="分享"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"a
        android:background="#000000"
        android:layout_weight="1"
        android:id="@+id/group">
        <RadioButton
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/bottom_first"
            android:button="@null"
            android:checked="true"
            android:textSize="11sp"
            android:background="@drawable/firstcheck" />
        <RadioButton
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/bottom_message"
            android:button="@null"
            android:textSize="11sp"
            android:background="@drawable/first2x"
            />
        <RadioButton
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/bottom_task"
            android:button="@null"
            android:background="@drawable/first2x"
            />
        <RadioButton
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/bottom_milestone"
            android:button="@null"
            android:background="@drawable/first2x"
            />
        <RadioButton
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/bottom_mine"
            android:button="@null"
            android:gravity="center"
            android:background="@drawable/first2x"
            />
    </RadioGroup>


</LinearLayout>



0 0
原创粉丝点击