2014-05-13 27 views
1

我遵循本教程中有關解析JSON的內容。所有工作都應該按照我的需要進行編輯。我正在獲取有關「服務器」的信息,其中一個字段是「狀態」(UP或DOWN)。根據變量在單個列表視圖中更改文本顏色

編輯:忘了張貼教程鏈接http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

目前,它看起來像這樣:http://puu.sh/8Ky0B.jpg 以上是發生了什麼,然後應用程序被加載。點擊一次就是當單個項目被點擊時它開始一個新的活動並單獨顯示這些信息。

你可以看到第二個服務器的狀態是「向下」。基於此,我想將文字顏色更改爲紅色,並將其保持爲綠色。

我怎麼能做到這一點,當它經過,並將每個列表視圖?

這裏是一個(當前)基本上是一樣的教程的代碼:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    serverList = new ArrayList<HashMap<String, String>>(); 

    ListView lv = getListView(); 

    // Listview on item click listener 
    lv.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 
      // getting values from selected ListItem 
      String name = ((TextView) view.findViewById(R.id.name)) 
        .getText().toString(); 
      String ip = ((TextView) view.findViewById(R.id.ipAddress)) 
        .getText().toString(); 
      String status = ((TextView) view.findViewById(R.id.serverStatus)) 
        .getText().toString(); 

      // Starting single server activity 
      Intent in = new Intent(getApplicationContext(), 
        SingleContactActivity.class); 
      in.putExtra(TAG_NAME, name); 
      in.putExtra(TAG_IP, ip); 
      in.putExtra(TAG_STATUS, status); 
      startActivity(in); 
     } 
    }); 

    // Calling async task to get json 
    new GetContacts().execute(); 
} 

/** 
* Async task class to get json by making HTTP call 
* */ 
private class GetContacts extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Please wait..."); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    @Override 
    protected Void doInBackground(Void... arg0) { 
     // Creating service handler class instance 
     ServiceHandler sh = new ServiceHandler(); 

     // Making a request to url and getting response 
     String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

     Log.d("Response: ", "> " + jsonStr); 

     if (jsonStr != null) { 
      try { 
       JSONArray jArray = new JSONArray(jsonStr); 

       // looping through All Servers 
       for (int i = 0; i < jArray.length(); i++) { 
        JSONObject c = jArray.getJSONObject(i); 

        String id = c.getString(TAG_ID); 
        String name = c.getString(TAG_NAME); 
        String ip = c.getString(TAG_IP); 
        String status = c.getString(TAG_STATUS); 

        // tmp hashmap for single server 
        HashMap<String, String> contact = new HashMap<String, String>(); 

        contact.put(TAG_ID, id); 
        contact.put(TAG_NAME, name); 
        contact.put(TAG_IP, ip); 
        contact.put(TAG_STATUS, status); 

        // adding server to server list 
        serverList.add(contact); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 

     ListAdapter adapter = new SimpleAdapter(
       MainActivity.this, serverList, 
       R.layout.list_item, new String[] { TAG_NAME, TAG_IP, 
         TAG_STATUS }, new int[] { R.id.name, 
         R.id.ipAddress, R.id.serverStatus }); 

     setListAdapter(adapter); 
    } 

} 
+3

如果您想自定義像這樣的列表項,請使用自定義適配器。 –

回答

0

在列表適配器的定義中,在getView()方法,找到的TextView並改變文本的顏色。

TextView tv = (TextView) listItem.findViewById(R.id.server_status); 
tv.setTextColor(android.R.color.primary_text_dark); 
1

你需要做一個自定義的適配器和getView(),你應該檢查服務器的狀態爲關閉則對應的TextView的顏色設置爲紅色否則將其設置爲綠色。

您getView()想爲以下幾點:(這僅僅是你的代碼的藍圖)

getView(){ 
    String serverstatus = server.getStatus(); 
    // get status should be method in method in model class for server. 
    if(serverstatus.equals("DOWN")){ 
     tv.setTextColor(Color.RED); 
    }else{ 
     tv.setTextColor(Color.GREEN); 
    } 
} 

編輯

  1. 做一個模型類。 Server類型的
class Server{ 
    String serverName, serverIp, serverStatus; 
     // getter and setter. 
    } 
  1. 並使陣列適配器。

  2. 在適配器的getView()膨脹的行項目,並設置細節。因爲已經添加了紅色字體藍圖。

+0

我在看這個:http://www.vogella.com/tutorials/AndroidListView/article.html但是我做了PostExecute例如替換此: ListAdapter適配器=新SimpleAdapter( MainActivity.this,SERVERLIST, R.layout.list_item,新的String [] {TAG_NAME,TAG_IP, TAG_STATUS},新的INT [] {R.id.name, ř .id.ipAddress,R.id.serverStatus}); setListAdapter(adapter); 對不起,我自己還沒有使用自定義適配器。 – user3406647

+0

這是很有用的教程,在14.2節中。教程:域模型和行交互「,解釋了這種方法。 – guptakvgaurav

+0

是的,在'onPostExecute()'你可以完成這項工作,因爲設置適配器在UI線程上工作,'onPostExecute()'也在UI線程上運行。所以你可以在onPostExecute()中設置適配器 – guptakvgaurav

0

採取定製適配器(一個BaseAdapter),而不是簡單的適配器,

有你在getView執行您的操作()方法。

0

你已經完成了大部分的辛勤工作已經:)

首先創建一個對象存儲服務器的詳細信息,而不是一個HashMap(這是緩慢而沉重的),加上一個目的是更加適應和適合你的目的更好。

我創建了一個超快速的例子(沒有完成,以你的細節,但應該很容易擴展)。

package com.example.adaptertest; 

public class HolderServer { 

String serverName; 
boolean isServerUp; 

public HolderServer(String serverName, boolean isServerUp) { 
    this.serverName = serverName; 
    this.isServerUp = isServerUp; 
} 

public String getServerName() { 
    return serverName; 
} 

public void setServerName(String serverName) { 
    this.serverName = serverName; 
} 

public boolean isServerUp() { 
    return isServerUp; 
} 

public void setServerUp(boolean isServerUp) { 
    this.isServerUp = isServerUp; 
} 
} 

接下來,您需要創建一個自定義適配器。在你的例子中,你實際上使用了一個簡單的適配器(ListAdapter adapter = new SimpleAdapter(),這是一個很好的第一步,但我們可以通過擴展它來改進一點,這將允許我們改變每個單獨元素在ListView即改變顏色等

這裏有一個簡單的例子:

package com.example.adaptertest; 

import java.util.ArrayList; 

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

public class AdapterServers extends ArrayAdapter<HolderServer>{ 

ArrayList<HolderServer> mServers = new ArrayList<HolderServer>(); 
private LayoutInflater mInflater; 
Context mContext; 

public AdapterServers(Context context, int resource, ArrayList<HolderServer> servers) { 
    super(context, resource, servers); 
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    mContext = context; 
    mServers = servers; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    //Inflate view for each element in list. 
    convertView = mInflater.inflate(R.layout.server_list_item, null); 

    //Get details for current server 
    HolderServer server = mServers.get(position); 

    //Set server name 
    ((TextView) convertView.findViewById(R.id.server_list_item_txt_servername)).setText(server.getServerName()); 

    //Now we set the status text and color 
    TextView status = (TextView) convertView.findViewById(R.id.server_list_item_txt_serverstatus); 
    if(server.isServerUp){ 
     status.setText(mContext.getResources().getString(R.string.up)); 
     status.setTextColor(mContext.getResources().getColor(R.color.green)); 
    }else{ 
     status.setText(mContext.getResources().getString(R.string.down)); 
     status.setTextColor(mContext.getResources().getColor(R.color.red)); 
    } 

    return convertView; 
} 
} 

現在回到你的代碼,先在的onCreate創建對象的一個​​新的列表:

ArrayList<HolderServer> mServerList = new ArrayList<HolderServer>(); 

然後而不是:

   // tmp hashmap for single server 
       HashMap<String, String> contact = new HashMap<String, String>(); 

       contact.put(TAG_ID, id); 
       contact.put(TAG_NAME, name); 
       contact.put(TAG_IP, ip); 
       contact.put(TAG_STATUS, status); 

您將創建新對象&將其添加到列表中。一旦你的HolderServer對象更新了您的變量顯然更新:

HolderServer server = new HolderServer("Server1", true); 
    serverList.add(server); 

然後該列表適用於適配器和適配器適用於列表視圖:

AdapterServers adapter = new AdapterServers(this, 0, serverList); 
    ((ListView) findViewById(R.id.fragment_main_listview)).setAdapter(adapter); 

祝你好運!

相關問題