欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

ListAdapter MyAdapter

程序员文章站 2022-03-20 23:01:16
ListAdapterpackage com.gcu.simple.adapter;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import com.bumpte...

ListAdapter

package com.gcu.simple.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.gcu.simple.R;
import com.gcu.simple.model.ImageInfo;

import java.util.List;

public class ListAdapter extends BaseAdapter {
    List<ImageInfo> dataList;
    Context context;

    public ListAdapter(List<ImageInfo> dataList, Context context){
        this.dataList = dataList;
        this.context = context;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if(convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.item_list, null);
            convertView.setTag(viewHolder);

            viewHolder.imageView = convertView.findViewById(R.id.imageView);
        }else{
            viewHolder = (ViewHolder)convertView.getTag();
        }
        Glide.with(context).load(dataList.get(position).imageUrl).into(viewHolder.imageView);
        return convertView;
    }

    @Override
    public Object getItem(int position) {
        return dataList.get(position);
    }

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

    class ViewHolder {
        ImageView imageView;
    }

    public void update(List<ImageInfo> data){
        dataList = data;
        notifyDataSetChanged();
    }
}

MyAdapter

package com.gcu.simple.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.gcu.simple.R;

import java.util.List;

public class MyAdapter extends BaseAdapter {
    private List<String> contents;
    Context context;
    @Override
    public int getCount() {
        return contents.size();
    }

    @Override
    public Object getItem(int position) {
        return contents.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null){
            // 初始化viewHolder
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.item_list, null);
            convertView.setTag(viewHolder);

        }else{
            // 复用旧对象
            viewHolder = (ViewHolder)convertView.getTag();
        }
        // 设置textview内容
        viewHolder.textView.setText(contents.get(position));
        return convertView;
    }

    class ViewHolder {
        TextView textView;
    }
}

Model
imageinfo

package com.gcu.simple.model;

public class ImageInfo {
    public String imageUrl;
    public String text;

    public ImageInfo(String imageUrl, String text){
        this.imageUrl = imageUrl;
        this.text = text;
}
}

mymodel

package com.gcu.simple.model;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.util.List;

public class MyModel extends ViewModel {
    private MutableLiveData<String> msg;
    private MutableLiveData<Integer> count;

    private  MutableLiveData<List<ImageInfo>> data;

    public MutableLiveData<Integer> getCount() {
        if (count == null) {
            count = new MutableLiveData<>();
        }
        return count;
    }

    public MutableLiveData<String> getMsg() {
        if (msg == null) {
            msg = new MutableLiveData<>();
        }
        return msg;
    }

    public MutableLiveData<List<ImageInfo>> getData() {
       if(data == null){
           data = new MutableLiveData<>();
       }
        return data;
    }
}

NETWORK
infoActivity

package com.gcu.simple;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.Bundle;

public class InfoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);

        Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(myToolbar);
    }
}

InfoFragment

package com.gcu.simple;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.gcu.simple.model.MyModel;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link InfoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class InfoFragment extends Fragment {
    private MyModel model;
    EditText editText;
    TextView textView;
    public InfoFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static InfoFragment newInstance() {
        InfoFragment fragment = new InfoFragment();
        return fragment;
    }

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

        model = new ViewModelProvider(getActivity()).get(MyModel.class);

        model.getMsg().observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                textView.setText(s);
            }
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        textView = view.findViewById(R.id.info_text);
        editText = view.findViewById(R.id.editTextInput);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                model.getMsg().setValue(s.toString());
            }
        });

        Intent intent = getActivity().getIntent();
        String msg = intent.getStringExtra(MainActivity.INFOKEY);
        textView.setText(msg);
        editText.setText(msg);


    }

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

ListActivity

package com.gcu.simple;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.database.Observable;
import android.os.Bundle;
import android.util.Log;

import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.gcu.simple.adapter.ListAdapter;
import com.gcu.simple.model.ImageInfo;
import com.gcu.simple.model.MyModel;
import com.gcu.simple.network.MySingleton;

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

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

public class ListActivity extends AppCompatActivity {
    MyModel model;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        model = new ViewModelProvider(this).get(MyModel.class);

        ListView listView = findViewById(R.id.listView);
        final ListAdapter adapter = new ListAdapter(new ArrayList<ImageInfo>(), getApplicationContext());
        listView.setAdapter(adapter);

        model.getData().observe(this, new Observer<List<ImageInfo>>(){

            @Override
            public void onChanged(List<ImageInfo> imageInfos) {
                if (imageInfos == null)
                    return;
                adapter.update(imageInfos);
            }
        });

        //Glide.with(getApplicationContext()).load(dataList.get(position).imageUrl).into(ListAdapter.ViewHolder.imageView);
        getData();
    }

    void getData() {
        RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).
                getRequestQueue();

        String url = "https://bing.getlove.cn/latelyBingImageStory";
        JsonArrayRequest jsonObjectRequest = new JsonArrayRequest
                (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {


                    @Override
                    public void onResponse(JSONArray response) {
                        //textView.setText("Response: " + response.toString());
                        Log.v("awtt1", String.format("111:%s", response.toString()));
                        JSONArray ar = null;
                        try {
                            ar = response;
                            Log.v("awtt1", String.format("111:%d", ar.length()));
                            List<ImageInfo> rets = new ArrayList<>();
                            for (int i = 0; i < ar.length(); i++) {
                                JSONObject item = ar.getJSONObject(i);
                                String text = item.getString("copyright");
                                String url = item.getString("CDNUrl");
                                url = String.format("https:%s", url);
                                rets.add(new ImageInfo(url, text));
                                Log.v("awtt1", String.format("%s, %s", url, text));
                            }
                            model.getData().setValue(rets);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), String.format("网络错误:%s", error), Toast.LENGTH_SHORT).show();
                        Log.e("wtt", String.format("%s", error));
                    }

                });
        queue.add(jsonObjectRequest);



    }

    void getData2(){
        final TextView textView = (TextView) findViewById(R.id.text);
        // ...

        // 初始化 RequestQueue.
        RequestQueue queue2 = Volley.newRequestQueue(this);

        // 发起一个StringRequest 请求指定网址
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://www.gcu.edu.cn/main.htm",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // 在textview控件上显示最多500个字符的内容
                        textView.setText("Response is: "+ response.substring(0,500));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 有错误是,显示: 请求数据报错!
                textView.setText("请求数据报错!");
            }
        });

        // 放置到调度队列.
        queue2.add(stringRequest);
    }
}

MainActivity

package com.gcu.simple;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    public static final String INFOKEY = "com.gcu.simple.infokey";
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
    }

    public void openMessage(View view){
        Intent intent = new Intent(this, InfoActivity.class);
        String msg = textView.getText().toString();
        intent.putExtra(INFOKEY, msg);
        startActivity(intent);
    }

    public void listBtn(View view){
        Intent intent = new Intent(this, ListActivity.class);
        startActivity(intent);
    }
}

STYLE

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    </style>

    <style name="button_text" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">#FF0000</item>
        <item name="android:textStyle">italic</item>

    </style>

    <style name="button_text.mytextstyle" >
        <item name="android:textSize">30sp</item>
        <item name="android:textStyle">bold</item>
    </style>
</resources>

LAYOUT
activity_info.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".InfoActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/fragment"
        android:name="com.gcu.simple.InfoFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_list.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".ListActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="1dp"
        android:layout_marginEnd="1dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0">

        <Button
            android:id="@+id/btn_msg"
            android:text="查看消息"
            android:onClick="openMessage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
             />

        <TextView
            android:id="@+id/textView"
            android:text="什么都没有"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginBottom="8dp"
             />

        <Button
            android:id="@+id/btn_data"
            android:text="数据更新及列表"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="listBtn"
             />

        <Button
            android:id="@+id/btn_style"
            style="@style/button_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="使用样式" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

fragment_info.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="@+id/infoLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InfoFragment">

    <!-- TODO: Update blank fragment layout -->

    <TextView
        android:id="@+id/info_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/hello_blank_fragment"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/info_text" />

</androidx.constraintlayout.widget.ConstraintLayout>

item_list.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />
</androidx.constraintlayout.widget.ConstraintLayout>

本文地址:https://blog.csdn.net/weixin_43865875/article/details/110583408