1. 程式人生 > >MVP登入展示專案初版

MVP登入展示專案初版

這個專案包含了,mvp框架,自動登入,資料庫記住密碼,多條目展示,輪播圖,二維碼展示等等,
在這裡插入圖片描述在這裡插入圖片描述
匯入jar包ImageLode.jar,zing.jar
黃油刀
implementation ‘com.jakewharton:butterknife:8.8.1’
annotationProcessor ‘com.jakewharton:butterknife-compiler:8.8.1’
清單檔案裡的東西填好
許可權

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

把Bean裡的寫好吧
Result自己寫下

package com.baidu.logindemo.bean;

public class Result<T> {
private String msg;
private String code;
private T data;

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public T getData() {
    return data;
}

public void setData(T data) {
    this.data = data;
}
}

User類裡用這個介面之封裝data的東西
http://www.zhaoapi.cn/user/login?mobile=15210369901&password=123456

private Object age;
private String appkey;
private String appsecret;
private String createtime;
private Object email;
private Object fans;
private Object follow;
private Object gender;
private Object icon;
private Object latitude;
private Object longitude;
private String mobile;
private Object money;
private Object nickname;
private String password;
private Object praiseNum;
private String token;
private int uid;
private Object userId;
private String username;

NewsBean 裡也是data裡的封裝
http://www.xieast.com/api/news/news.php?page=1

private String uniquekey;
private String title;
private String date;
private String category;
private String author_name;
private String url;
private String thumbnail_pic_s;
private String thumbnail_pic_s02;
private String thumbnail_pic_s03;

寫M層有LoginModel,NewModel,NewsModel
LoginModel

public class LoginModel {
public static Result<User> LoginData(String name,String pwd){
    HttpUtils httpUtils = HttpUtils.getHttpUtils();
    String json = httpUtils.get("http://www.zhaoapi.cn/user/login?mobile=" + name + "&password=" + pwd);

    Gson gson = new Gson();
    Type type = new TypeToken<Result<User>>() {}.getType();
    Result result = gson.fromJson(json, type);
    //Log.i(TAG, "LoginData: "+result.getCode());
    return result;
}
}

NewModel

public class NewModel {
public static Result LoginData(String name, String pwd) {
    HttpUtils httpUtils = HttpUtils.getHttpUtils();
    String json = httpUtils.get("http://www.zhaoapi.cn/user/reg?mobile=" + name + "&password=" + pwd);

    Gson gson = new Gson();
    //Type type = new TypeToken<Result<User>>() {}.getType();
    Result result = gson.fromJson(json, Result.class);
    //Log.i(TAG, "LoginData: "+result.getCode());
    return result;
}
}

NewsModel

 public class NewsModel {
public static Result LoginData(String page) {
    HttpUtils httpUtils = HttpUtils.getHttpUtils();
    String json = httpUtils.get("http://www.xieast.com/api/news/news.php?page=" + page);

    Gson gson = new Gson();
    Type type = new TypeToken<Result<List<NewsBean>>>() {}.getType();
    Result result = gson.fromJson(json, type);
    return result;
}
}

P層LoginPresenter,MyPresenter,NewPresenter,BasePresenter,NewsPresenter
LoginPresenter

public class LoginPresenter extends MyPresenter {
public LoginPresenter(BaseLogin baseLogin) {
    super(baseLogin);
}

@Override
public Result<User> userModel(String... args) {
    return LoginModel.LoginData(args[0],args[1]);
}
}

MyPresenter

public abstract class MyPresenter {
private BaseLogin baseLogin;
private static final String TAG = "MyPresenter---";
public  MyPresenter (BaseLogin baseLogin) {
    this.baseLogin = baseLogin;
}
public void unLoginCall(){
    baseLogin = null;
}

public void request(final String ...strings){
    new MaTask().execute(strings);

}
class MaTask extends AsyncTask<String,Void,Result> {


    protected Result doInBackground(String... strings) {
        Result<User> result = userModel(strings);
        Log.i(TAG, "doInBackground: "+result.getMsg());
        return result;
    }

    protected void onPostExecute(Result result) {
        super.onPostExecute(result);
        if (result.getCode().equals("0")){
            baseLogin.loginSuccess(result.getData());
        }else{
            baseLogin.loginError(result);
        }
    }
}
public abstract Result<User> userModel(String ... args);
}

NewPresenter

public class NewPresenter extends MyPresenter {
public NewPresenter(BaseLogin baseLogin) {
    super(baseLogin);
}

@Override
public Result<User> userModel(String... args) {
    return NewModel.LoginData(args[0],args[1]);
}
}

BasePresenter拷貝MyPresenter 改result.getCode().equals(“1”)

public abstract class BasePresenter {
private BaseLogin baseLogin;
private static final String TAG = "MyPresenter---";
public BasePresenter(BaseLogin baseLogin) {
    this.baseLogin = baseLogin;
}
public void unLoginCall(){
    baseLogin = null;
}

public void request(final String ...strings){
    new MaTask().execute(strings);

}
class MaTask extends AsyncTask<String,Void,Result> {


    protected Result doInBackground(String... strings) {
        Result<User> result = userModel(strings);
        Log.i(TAG, "doInBackground: "+result.getMsg());
        return result;
    }

    protected void onPostExecute(Result result) {
        super.onPostExecute(result);
        if (result.getCode().equals("1")){
            baseLogin.loginSuccess(result.getData());
        }else{
            baseLogin.loginError(result);
        }
    }
}
public abstract Result<User> userModel(String ... args);
}

NewsPresenter

public class NewsPresenter extends BasePresenter {
public NewsPresenter(BaseLogin baseLogin) {
    super(baseLogin);
}

@Override
public Result<User> userModel(String... args) {
    return NewsModel.LoginData(args[0]);
}

}

Utils包裡寫HttpUtils

public class HttpUtils {
private static HttpUtils httpUtils = new HttpUtils();
private HttpUtils(){

}

public static HttpUtils getHttpUtils() {
    synchronized (httpUtils){
        if (httpUtils==null){
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }
}
public String get(String urls){
    try {
        URL url = new URL(urls);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5000);
        if (con.getResponseCode()==HttpURLConnection.HTTP_OK){
            InputStream inputStream = con.getInputStream();
            String string = getString(inputStream);
            return string;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

private String getString(InputStream inputStream) throws IOException {
    InputStreamReader reader = new InputStreamReader(inputStream);
    char[] chars = new char[1024];
    StringBuffer buffer = new StringBuffer();
    int v=0;
    while ((v=reader.read(chars))!=-1){
        String s = new String(chars,0,v);
        buffer.append(s);
    }
    return buffer.toString();
}
}

寫資料庫helper包裡Myhelper

public class Myhelper extends SQLiteOpenHelper {


public Myhelper(@Nullable Context context) {
    super(context, "bw.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table user(_id integer primary key autoincrement,name varchar(20),pwd varchar(20))");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

app包裡寫Myapp

public class Myapp extends Application {
private static Context context;

@Override
public void onCreate() {
    super.onCreate();
    context=this;

    ImageLoaderConfiguration build = new ImageLoaderConfiguration.Builder(this).build();
    ImageLoader.getInstance().init(build);
}
private ImageLoaderConfiguration getconfig() {
    File file = new File(Environment.getExternalStorageDirectory()+"/image");
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration
            .Builder(this)
            .diskCache(new UnlimitedDiskCache(file))
            .build();
    return configuration;
}
public static DisplayImageOptions getOptions(){
    DisplayImageOptions options = new DisplayImageOptions
            .Builder()
            .showImageOnFail(R.mipmap.ic_launcher)
            .showImageOnLoading(R.mipmap.ic_launcher)
            .cacheOnDisk(true)
            .cacheInMemory(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();
    return options;
}
public static Context getContext() {
    return context;
}
}

一定要在清單配置

  android:name=".app.Myapp"

寫Core裡的介面BaseLogin

package com.baidu.logindemo.core;
import com.baidu.logindemo.bean.Result;

public interface BaseLogin<T> {
	void loginSuccess(T data);
	void loginError(Result result);
}

首先寫出主頁面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:gravity="center"
tools:context=".activity.loginActivity">
<LinearLayout
    android:layout_width="250dp"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="姓名:"/>
    <EditText
        android:id="@+id/edit_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
    android:layout_width="250dp"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="密碼:"/>
    <EditText
        android:id="@+id/edit_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"/>
</LinearLayout>
<RelativeLayout
    android:layout_width="250dp"
    android:layout_height="wrap_content">
    <CheckBox
        android:id="@+id/check_zd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="自動登入"/>
    <CheckBox
        android:id="@+id/check_jz"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_alignParentRight="true"
        android:text="記住密碼"/>
</RelativeLayout>
<RelativeLayout
    android:layout_width="200dp"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/but_dl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="登入"/>
    <Button
        android:id="@+id/but_zc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_alignParentRight="true"
        android:text="註冊"/>

</RelativeLayout>
</LinearLayout>

主Activity繼承介面

public class loginActivity extends AppCompatActivity implements BaseLogin {

@BindView(R.id.edit_name)
EditText editName;
@BindView(R.id.edit_pwd)
EditText editPwd;
@BindView(R.id.check_zd)
CheckBox checkZd;
@BindView(R.id.check_jz)
CheckBox checkJz;
@BindView(R.id.but_dl)
Button butDl;
@BindView(R.id.but_zc)
Button butZc;
private SharedPreferences preferences;
private LoginPresenter presenter;
private String pwds;
private Button but_three_login;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    ButterKnife.bind(this);

    preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
    boolean zd = preferences.getBoolean("zd", false);
    boolean jz = preferences.getBoolean("jz", false);
    String name = preferences.getString("name", "");
    String pwd = preferences.getString("pwd", "");
    checkJz.setChecked(jz);
    checkZd.setChecked(zd);
    if (zd) {
        Intent intent = new Intent(loginActivity.this, MiActivity.class);
        startActivity(intent);
        finish();
    } else {
        if (jz) {
            editName.setText(name);
            editPwd.setText(pwd);
        } else {
            editName.setText(name);
            editPwd.setText("");
        }
    }
    presenter = new LoginPresenter(this);

}


@OnClick({R.id.but_dl, R.id.but_zc})
public void onViewClicked(View view) {
    switch (view.getId()) {
        case R.id.but_dl:
            pwds = editPwd.getText().toString();
            String name = editName.getText().toString();

            presenter.request(name, pwds);
            break;
        case R.id.but_zc:
            Intent intent = new Intent(loginActivity.this,MaActivity.class);
            startActivityForResult(intent,100);
            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==100 && resultCode == 110){
        String name = data.getStringExtra("name");
        String pwd = data.getStringExtra("pwd");
        editName.setText(name);
        editPwd.setText(pwd);
    }
}

@Override
public void loginSuccess(Object data) {
    User user= (User) data;
    boolean zd = checkZd.isChecked();
    boolean jz = checkJz.isChecked();
    SharedPreferences.Editor edit = preferences.edit();
    edit.putBoolean("zd",zd);
    edit.putBoolean("jz",jz);
    edit.putString("name",user.getMobile());
    edit.putString("pwd",pwds);
    edit.commit();
    Toast.makeText(this, user.getMobile(), Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(loginActivity.this,MiActivity.class);

    startActivity(intent);
    finish();
}

@Override
public void loginError(Result result) {
    Toast.makeText(this, result.getMsg(), Toast.LENGTH_SHORT).show();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    presenter.unLoginCall();
}
}

註冊介面
佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".activity.MiActivity">
<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="10"/>
<RadioGroup
    android:id="@+id/radio_group"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal"
    android:layout_weight="1">
    <RadioButton
        android:id="@+id/radio_1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:button="@null"
        android:text="展示介面"
        android:checked="true"
        android:background="@drawable/checked_selector"
        />
    <RadioButton
        android:id="@+id/radio_2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:button="@null"
        android:text="我的名片"
        android:background="@drawable/checked_selector"
        />
</RadioGroup>
</LinearLayout>

Activity裡

public class MaActivity extends AppCompatActivity implements BaseLogin {

@BindView(R.id.edit_name_new)
EditText editNameNew;
@BindView(R.id.edit_pwd_new)
EditText editPwdNew;
@BindView(R.id.but_dl_new)
Button butDlNew;
@BindView(R.id.but_black)
Button butBlack;
private String name;
private String pwd;
private NewPresenter presenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ma);
    ButterKnife.bind(this);
    presenter = new NewPresenter(this);
}

@OnClick({R.id.but_dl_new, R.id.but_black})
public void onViewClicked(View view) {
    switch (view.getId()) {
        case R.id.but_dl_new:
            name = editNameNew.getText().toString();
            pwd = editPwdNew.getText().toString();
            presenter.request(name, pwd);
            break;
        case R.id.but_black:
            finish();
            break;
    }
}

@Override
public void loginSuccess(Object data) {
    Intent intent = new Intent();
    intent.putExtra("name",name);
    intent.putExtra("pwd",pwd);
    setResult(110,intent);
    finish();
}

@Override
public void loginError(Result result) {
    Toast.makeText(this, result.getMsg(), Toast.LENGTH_SHORT).show();
}
}

登入介面有跳轉MiActivity主介面
佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".activity.MiActivity">
<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="10"/>
<RadioGroup
    android:id="@+id/radio_group"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal"
    android:layout_weight="1">
    <RadioButton
        android:id="@+id/radio_1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:button="@null"
        android:text="展示介面"
        android:checked="true"
        android:background="@drawable/checked_selector"
        />
    <RadioButton
        android:id="@+id/radio_2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:button="@null"
        android:text="我的名片"
        android:background="@drawable/checked_selector"
        />
</RadioGroup>
</LinearLayout>

自定義的佈局寫drawable裡
@drawable/checked_selector

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

Activity裡

public class MiActivity extends AppCompatActivity {

@BindView(R.id.view_pager)
ViewPager viewPager;
@BindView(R.id.radio_1)
RadioButton radio1;
@BindView(R.id.radio_2)
RadioButton radio2;
@BindView(R.id.radio_group)
RadioGroup radioGroup;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mi);
    ButterKnife.bind(this);
    List<Fragment> list = new ArrayList<>();
    list.add(new Fragment1());
    list.add(new Fragment2());
    MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),list);
    viewPager.setAdapter(adapter);
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            radioGroup.check(radioGroup.getChildAt(position).getId());
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId){
                case R.id.radio_1:
                    viewPager.setCurrentItem(0,false);
                    break;
                case R.id.radio_2:
                    viewPager.setCurrentItem(1,false);
                    break;
            }
        }
    });


}
}

可以寫Fragment
fragment1的佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.youth.banner.Banner android:id="@+id/banner"
    android:layout_width="match_parent"
    android:layout_height="300dp">
</com.youth.banner.Banner>

<com.handmark.pulltorefresh.library.PullToRefreshListView
    android:id="@+id/pull"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
    </LinearLayout>

Fragment1

public class Fragment1 extends Fragment implements BaseLogin {
private static final String TAG = "Fragment1----------";
private PullToRefreshListView listView;
private NewsPresenter newsPresenter;
private int  type=0;
private List<NewsBean> lists = new ArrayList<>();
private View view;
String[] url={"http://ww4.sinaimg.cn/large/006uZZy8jw1faic21363tj30ci08ct96.jpg",
        "http://ww4.sinaimg.cn/large/006uZZy8jw1faic259ohaj30ci08c74r.jpg",
        "http://ww4.sinaimg.cn/large/006uZZy8jw1faic2e7vsaj30ci08cglz.jpg",
        "http://ww4.sinaimg.cn/large/006uZZy8jw1faic2b16zuj30ci08cwf4.jpg"};
private Banner banner;
public Fragment1() {
    // Required empty public constructor
}
private int page = 1;


public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_fragment1, container, false);
    listView = view.findViewById(R.id.pull);
    listView.setScrollingWhileRefreshingEnabled(true);
    listView.setMode(PullToRefreshBase.Mode.BOTH);
    listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            page=1;
            type = 0;
            newsPresenter.request(page+"");
            listView.onRefreshComplete();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            page++;
            type = 1;
            newsPresenter.request(page+"");
            listView.onRefreshComplete();
        }
    });
    return view;
}

@Override
public void onActivityCreated( Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    newsPresenter = new NewsPresenter(this);
    newsPresenter.request(page+"");
}

@Override
public void loginSuccess(Object data) {
    List<NewsBean> list = (List<NewsBean>) data;

    // Log.i(TAG, "loginSuccess: "+list.get(0).toString());
    //Toast.makeText(getActivity(), list.get(0).getTitle(), Toast.LENGTH_SHORT).show();
    switch (type){
        case 0:
            MyAdapter adapter = new MyAdapter(getActivity(),list);
            listView.setAdapter(adapter);
            break;
        case 1:
            lists.addAll(list);
            MyAdapter adapters = new MyAdapter(Myapp.getContext(),lists);
            listView.setAdapter(adapters);
            break;
    }

    //找控制元件
    banner = view.findViewById(R.id.banner);
    //設定圖片載入器
    banner.setImageLoader(new BannerImageLoader());
    //設定圖片集合
    banner.setImages(Arrays.asList(url));
    //條用
    banner.start();

}

@Override
public void loginError(Result result) {

}
private class BannerImageLoader extends ImageLoader {

    @Override
    public void displayImage(Context context, Object path, ImageView imageView) {
        com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
        imageLoader.displayImage((String) path,imageView);

    }
}
}

fragment2的佈局

<ImageView
    android:id="@+id/imageView"
    android:layout_width="300dp"
    android:layout_height="300dp"
    app:srcCompat="@android:color/background_light"
    />
<Button
    android:id="@+id/but_new"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="退出登入"/>

Fragment2

public class Fragment2 extends Fragment {
private ImageView imageView;
private ImageView im1;
private int w,h;        //圖片寬度w,高度h
private String name;
private Button button;

public Fragment2() {
    // 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_fragment2, container, false);
    imageView = view.findViewById(R.id.imageView);
    button = view.findViewById(R.id.but_new);

    return view;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser){
        SharedPreferences preferences = Myapp.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        name = preferences.getString("name", "");
        //Toast.makeText(MyApp.getContext(), name, Toast.LENGTH_SHORT).show();
        createQRcodeImage(name);
    }
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Myapp.getContext(),loginActivity.class);
            startActivity(intent);
            getActivity().finish();
        }
    });
}

//轉換成二維碼QRcode的函式。引數為一個字串
public void createQRcodeImage(String url)
{
    im1=imageView;
    w=im1.getWidth();
    h=im1.getHeight();
    try
    {
        //判斷URL合法性
        if (url == null || "".equals(url) || url.length() < 1)
        {
            return;
        }
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //影象資料轉換,使用了矩陣轉換
        BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, w, h, hints);
        int[] pixels = new int[w * h];
        //下面這裡按照二維碼的演算法,逐個生成二維碼的圖片,
        //兩個for迴圈是圖片橫列掃描的結果
        for (int y = 0; y < h; y++)
        {
            for (int x = 0; x < w; x++)
            {
                if (bitMatrix.get(x, y))
                {
                    pixels[y * w + x] = 0xff000000;
                }
                else
                {
                    pixels[y * w + x] = 0xffffffff;
                }
            }
        }
        //生成二維碼圖片的格式,使用ARGB_8888
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
        //顯示到我們的ImageView上面
        im1.setImageBitmap(bitmap);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

列表的佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
    android:id="@+id/image_view"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:src="@mipmap/ic_launcher"/>
<TextView
    android:id="@+id/text_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="標題"
    android:textColor="#000"/>
    </LinearLayout>

在adapter 包裡寫MyFragmentPagerAdapter

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> list;
public MyFragmentPagerAdapter(FragmentManager fm, List<Fragment> list) {
    super(fm);
    this.list=list;

}

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

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

還有一個列表的適配
MyAdapter

public class MyAdapter extends BaseAdapter {
private Context context;
private List<NewsBean> list;

public MyAdapter(Context context, List<NewsBean> list) {
    this.context = context;
    this.list = list;
}

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

@Override
public Object 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;
    if (convertView==null){
        convertView=View.inflate(context, R.layout.itme_layout,null);
        holder = new ViewHolder();
        holder.imageView = convertView.findViewById(R.id.image_view);
        holder.textView = convertView.findViewById(R.id.text_title);
        convertView.setTag(holder);
    }else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.textView.setText(list.get(position).getTitle());
    ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(),holder.imageView,Myapp.getOptions());
   // Glide.with(context).load(list.get(position).getThumbnail_pic_s()).into(holder.imageView);
    return convertView;
}
public class ViewHolder{
    ImageView imageView;
    TextView textView;
}
}