JSON 数据绑定 TextView原理:
getResourceEntryName()获取资源名称,再通过资源名获取JSONObject中的值。
不过我并不推荐使用,推荐使用Android 官方DataBinding http://www.jianshu.com/p/38f0de2c9300
显示效果布局中的id名字使用json中的键名
main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/mLinearLayout"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
MainActivity .java
public class MainActivity extends Activity {
private OkHttpClient mOkHttpClient;
private XRecyclerViewAdapter xRecyclerViewAdapter;
private TextViewJsonBind mTextViewJsonBind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
View view= findViewById(R.id.mLinearLayout);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject("{\"title\":\"标题\",\"body\":\"bodybodybodybody\"}");
} catch (JSONException e) {
e.printStackTrace();
}
//初始化数据绑定
mTextViewJsonBind=new TextViewJsonBind(view);
//绑定jsonObject 数据
mTextViewJsonBind.setData(jsonObject);
}
}
TextViewJsonBind .java
/**
* TextView绑定json数据
* Created by cheng on 2016/9/5.
*/
public class TextViewJsonBind {
Map<String, TextView> map = new HashMap<>();
Context context;
View rootView;
/**
* 初始化
* @param view
*/
public TextViewJsonBind(View view) {
rootView = view;
context = view.getContext();
if (view instanceof ViewGroup) {
getTextViews((ViewGroup) view);
}
}
/**
* 设置json数据
* @param jsonObject
*/
public void setData(JSONObject jsonObject) {
Set<Map.Entry<String, TextView>> entries = map.entrySet();
//遍历存放在map中TextView,设置数据
for (Map.Entry<String, TextView> entry : entries) {
String key=entry.getKey();
entry.getValue().setText(jsonObject.optString(key));
}
}
/**
* 通过递归遍历获取ViewGroup 下所有继承TextView的空间,将其存放在map中,
* 避免每次绑定数据时findViewById降低效率
* @param ViewGroup
*/
private void getTextViews(ViewGroup viewGroup) {
if (viewGroup == null) {
return;
}
int count = viewGroup.getChildCount();
for (int i = 0; i < count; i++) {
View view = viewGroup.getChildAt(i);
if (view instanceof TextView) { // 若是TextView记录下
TextView newDtv = (TextView) view;
String key = context.getResources().getResourceEntryName(newDtv.getId());
map.put(key, newDtv);
} else if (view instanceof ViewGroup) {
// 若是布局控件(LinearLayout或RelativeLayout),继续查询子View
this.getTextViews((ViewGroup) view);
}
}
}
}
网友评论