Andorid 获取数据并填充到View
背景
在上次的博客中,进行了登录请求的实现,实现了客户端与服务端的交互并向服务端提交数据。这次就想着从服务端获取数据,并将数据展示在页面中。
构思
根据自己工作中遇到的的接口,很多都返回一个list。就想试着写一个页面来承载这些数据。根据看《Android第一行代码》看到RecycleView能够满足改需求。所以决定在上一次的代码基础上再加一个activity。
操作
- 查看数据返回构造响应的数据结构。因为在开发代码中已经有了对应的代码,所以我就直接进行了拷贝,省去写代码的时间。
- 编写布局文件,
- 整个布局文件activity_my_article.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:background="0x7f0801a2">-->
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"/>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
主要用到的布局控件:RecyclerView、Toolbar、CoordinatorLayout、AppBarLayout。Toolbar、CoordinatorLayout、AppBarLayout的介绍的文章,这里给出一篇介绍。关于RecyclerView的介绍网上资料也是比较多的,这里就不给了。
- 各个item布局 item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/item_layout">
<TextView
android:lineSpacingExtra="0dp"
android:textSize="20sp"
android:ellipsize="end"
android:layout_margin="20dp"
android:layout_height="wrap_content"
tools:text="文章标题文章标题文章标题文章标题文章标题"
android:includeFontPadding="false"
android:lineSpacingMultiplier="1.2"
android:gravity="top"
android:layout_width="match_parent"
android:id="@+id/my_article_item_title_txt"
android:maxLines="2"
android:textColor="#333333"
>
</TextView>
</LinearLayout>
这里的布局很简单主要就为了显示一个文本。设置了标题的大小间距等信息。
- 因为用到webview所以新增一个activity_web_view.xml文件。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
以上就是我们编写的布局。在以上用的一些:toolbar 、Recycleview、CoordinatorLayout、AppBarLayout都不是自有的,而是需要加入依赖。在模块buile.gradle中加入以下依赖:
compile 'com.android.support:recyclerview-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
因为我们设置了toolbar,所以不要再用自带的。所以在res/valus/stytles.xml中加入一个noActionbar的stytle.
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
应用这个styele到我们对应的activity中
xml <activity android:name=".MyArticleActivity" android:theme="@style/AppTheme.NoActionBar"> </activity>
- 编写适配器。代码如下
package LoginCore;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.weidian.login.R;
import com.weidian.login.WebViewActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by huxy on 2018/3/26.
*/
public class MyArticleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<QueryArticleResponse.ArticleInfo> articleData;
private Context context;
public MyArticleAdapter(Context context,List<QueryArticleResponse.ArticleInfo> articleData) {
this.context = context;
this.articleData=articleData;
}
private Context getContext(){
return context;
}
public List<QueryArticleResponse.ArticleInfo> getData() {
return articleData;
}
public void setData(QueryArticleResponse data) {
if (articleData == null) {
articleData = new ArrayList<>();
}
articleData.clear();
articleData.addAll(data.items);
notifyDataSetChanged();
}
public void appendData(QueryArticleResponse data) {
articleData.addAll(data.items);
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyArticleAdapter.MyArticleViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}
@Override
public int getItemCount() {
return articleData == null ? 0 : articleData.size();
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
bindItem((MyArticleViewHolder) holder, position);
//设置点击事件
((MyArticleViewHolder) holder).itemLayout.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(context, WebViewActivity.class);
((MyArticleViewHolder) holder).itemLayout.getContext().startActivity(intent);
}
});
}
private void bindItem(final MyArticleViewHolder holder, int position) {
if (articleData != null && articleData.size() > position) {
if (articleData != null && articleData.size() > position) {
final QueryArticleResponse.ArticleInfo data = articleData.get(position);
//设置title
holder.itemTitleTxt.setText(data.title);
holder.itemTitleTxt.setMaxLines(TextUtils.isEmpty(data.getCover()) ? 1 : 2);
}
}
}
public class MyArticleViewHolder extends RecyclerView.ViewHolder {
public LinearLayout itemLayout;
public TextView itemTitleTxt;
private MyArticleViewHolder(final View v) {
super(v);
itemTitleTxt = (TextView) v.findViewById(R.id.my_article_item_title_txt);
itemLayout = (LinearLayout) v.findViewById(R.id.item_layout);
}
}
}
关于Recycleview适配器的资料,这里给出一个链接RecyclerView.Adapter.这个是比较详细的,当然我们可以看一个更简单的简单Adapter。
- 编写activity
- 主要activity
public class MyArticleActivity extends AppCompatActivity {
private MyArticleAdapter adapter = new MyArticleAdapter(this, null);
private RecyclerView myArticleList;
private int allArticleNum = 0;
List<QueryArticleResponse.ArticleInfo> articlelist;
PageRequest pageRequest = new PageRequest();
ContextParam contextParam = new ContextParam();
Handler uiHandler = new Handler(Looper.getMainLooper());
private Toolbar toolbar;
public interface ResponseListner {
void RespondeSuccess(QueryArticleResponse result);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_article);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("所有文章");
//获得recycleview
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
//初始化数据
try {
initdata(new ResponseListner() {
@Override
public void RespondeSuccess(final QueryArticleResponse result) {
uiHandler.post(new Runnable() {
@Override
public void run() {
adapter.setData(result);
}
});
}
});
} catch (Exception e) {
e.printStackTrace();
}
//数据进入适配器
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//适配器与recyclerview绑定
recyclerView.setAdapter(adapter);
//设置分割线
recyclerView.addItemDecoration(new MyItemDecoration(this));
}
public void initdata(final ResponseListner responseListner) throws Exception {
pageRequest.setPageNumber(1);
pageRequest.setPageSize(20);
contextParam.appid = "XXXXX";
contextParam.userID = "XXXX";
contextParam.token = "_EwWqqVIQLLhIfAVLURTbiJEqVXo215LK_ERPbGbh7TxuaSdIl75oZXtT1u_roWxJTN2ph0RB1mTFwIQt5FKcE6tVF5P5rQrlbtUZjNLMFYl8jrBGIp4zWqMUOasXvXLxSHdETBdQfUwg9XdDZGccNQPwuvlBSJ8AzoOwIupwtk-OBvogN7I";
contextParam.wduss = "_EwWqqVIQLLhIfAVLURTbiJEqVXo215LK_ERPbGbh7TxuaSdIl75oZXtT1u_roWxJTN2ph0RB1mTFwIQt5FKcE6tVF5P5rQrlbtUZjNLMFYl8jrBGIp4zWqMUOasXvXLxSHdETBdQfUwg9XdDZGccNQPwuvlBSJ8AzoOwIupwtk-OBvogN7I";
contextParam.uss = "_EwWqqVIQLLhIfAVLURTbiJEqVXo215LK_ERPbGbh7TxuaSdIl75oZXtT1u_roWxJTN2ph0RB1mTFwIQt5FKcE6tVF5P5rQrlbtUZjNLMFYl8jrBGIp4zWqMUOasXvXLxSHdETBdQfUwg9XdDZGccNQPwuvlBSJ8AzoOwIupwtk-OBvogN7I";
contextParam.wduserID = "XXXX";
final QueryArticleResponse[] response = new QueryArticleResponse[1];
//发出请求
try {
HttpUtils.CheckResponse(pageRequest, contextParam, "需要填入url", new HttpUtils.OnRespondeSuccessListener() {
@Override
public void RespondeSuccess(JSONObject result) {
String result1 = result.getString("result");
//结果进行转换
response[0] = JSON.parseObject(result1, QueryArticleResponse.class);
responseListner.RespondeSuccess(response[0]);
}
});
} catch (IOException e) {
e.printStackTrace();
Log.e("请求异常", "not bussiness erro");
}
}
以上就是将适配器与Recycleview的绑定。数据来源于我们接口的请求。
- 编写webview的activity
我们写webbiew是针对于每一个item,都做了一个监听,只要点击item,webview.loadurl("http://wwww.baidu.com")
```java
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE,null);
webView.loadUrl("http://www.baidu.com");
}
关于MyArticleActivity的工作已经全部做完。现在两个activity之间还未连通。所以下面需要打通activity
- loginactivity 与MyArticleActivity打通
显性的使用Intent来进行跳转,代码如下:
private void postOnUIThread(final Map<String, String> result) {
et_username.post(new Runnable() {
@Override
public void run() {
if(Integer.parseInt(result.get("code"))==0){
Intent intent = new Intent(LoginActivity.this,MyArticleActivity.class);
//跳转到下一个activity
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(),result.get("description"),Toast.LENGTH_SHORT).show();
}
}
});
}
登录成功后就跳转到MyArticleActivity。
编译成功运行
点击登录,登录成功后跳转到MyArticleActivity
MyArticleActivity.jpeg
点击item项就跳转到百度
WebViewLoadUrl.jpeg
网友评论