如何用json在android中以编程方式添加文本视图

时间:2017-02-28 09:23:07

标签: android

朋友我想创建一个从JSON数组创建文本视图的应用程序 在例子中

"name":"Lenovo","price":"5000","description":"2 gb ram","type":"mobile"

它将更改它知道值并创建一个带有此标题名称,类型,价格的文本字段

2 个答案:

答案 0 :(得分:0)

您需要以某种方式使用您的json,使用gson之类的框架或JSONObject之类的类(如果需要,可以在网上找到)。

假设您有数据放入TextView,那么接下来您需要在活动中创建TextView

TextView textView = new TextView(this); //it need context
textView.setText(yourJSONObject.getText());

最后一部分是将TextView放到您的布局中(在本例中为linearLayout)。

yourLinearLayout.addView(addView(textVIew))

答案 1 :(得分:0)

试试这个.. 使用LinearLayout

创建布局
<LinearLayout
    android:orientation="vertical"
    android:id="@+id/linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</LinearLayout>

然后迭代你的json

LinearLayout linearLayout= (LinearLayout)findViewById(R.id.linear);     
linearLayout.removeAllViews();                             

Iterator<String> iter = new JSONObject("JSON STRING").keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);

        TextView textView= new TextView(this);              
        textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 48));
        textView.setGravity(Gravity.CENTER_VERTICAL);                       
        textView.setText(key+" : "+value.toString());                                    
        linearLayout.addView(textView);     


    } catch (JSONException e) {
        // Something went wrong!
    }
}