2016-07-19 2 views
-1

자바를 사용하여 listview의 배경색을 설정하고 싶습니다 ... 다음은 목록보기의 배경색을 설정하고자하는 코드입니다.
이름, 주소, varification 유형의 값은 서버에서옵니다. 이제 listview의 배경색을 빨강으로 설정하려고합니다.
는 이미 어떻게 여기 만 자바를이를 사용하여 수행 할 수자바를 사용하여 안드로이드에서 목록보기의 배경색을 설정하는 방법

public class GetLead extends ListActivity implements OnClickListener{ 

    private ProgressDialog pDialog; 

    // URL to get contacts JSON 
// private static String url = "104.25.125.70/verification/getCaf"; 

    // JSON Node names 

    private static final String TAG_ID = "cid"; 
    private static final String TAG_NAME = "name"; 
    private static final String TAG_EMAIL = "email"; 
// private static final String TAG_CONTACTS = "contacts"; 
//  
     String priority="high"; 
    private static final String TAG_ADDRESS = "address"; 
    private static final String TAG_STATUS = "status"; 

    private static final String TAG_VARTYPE = "verification"; 
    private long backPressedTime = 0; 

    GlobalClass gclass; 


    // contacts JSONArray 
    JSONArray contacts = null; 
    Button refresh, logout; 
    // Hashmap for ListView 
    ArrayList<HashMap<String, String>> contactList; 

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

     this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     //Remove notification bar 
     this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
     setContentView(R.layout.activity_getjson); 

    // startService(new Intent(this, LocationBackgroundService.class)); 
     contactList = 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 custid = ((TextView) view.findViewById(R.id.custId)) 
         .getText().toString(); 
       String name = ((TextView) view.findViewById(R.id.name)) 
         .getText().toString(); 
       String address = ((TextView) view.findViewById(R.id.address)) 
         .getText().toString(); 

       String verType = ((TextView) view.findViewById(R.id.verificationType)) 
         .getText().toString(); 

       // Starting single contact activity 

       if(verType.equals("reside")){ 
        Intent in = new Intent(getApplicationContext(), 
          resideVarStatusUpdate.class); 
        in.putExtra(TAG_ID, custid); 
        in.putExtra(TAG_NAME, name); 
        in.putExtra(TAG_ADDRESS, address); 
        startActivity(in); 
       } 
       else if(verType.equals("reside1")){ 
        Intent in = new Intent(getApplicationContext(), 
          reside1VarStatusUpdate.class); 
        in.putExtra(TAG_ID, custid); 
        in.putExtra(TAG_NAME, name); 
        in.putExtra(TAG_ADDRESS, address); 
        startActivity(in); 
       } 

      } 
     }); 

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

     refresh = ((Button) findViewById(R.id.refresh)); 
     refresh.setOnClickListener(this); 

     logout = ((Button) findViewById(R.id.logout)); 
     logout.setOnClickListener(this); 
    } 
    @Override 
    public void onClick(View v) { 
     if (v == refresh){ 
      new GetContacts().execute(); 
     } 
     else if (v == logout){ 
      this.finish(); 
     } 
    } 

    /** 
    * 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(GetLead.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      // Creating service handler class instance 
      String jsonStr = null; 
      // get user data from session 
      final GlobalClass globalVariable = (GlobalClass) getApplicationContext(); 

      ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
      postParameters.add(new BasicNameValuePair("id",globalVariable.getId())); 

      // email 
      try { 
       jsonStr = SimpleHttpClient 
         .executeHttpPost(
           "http://"+constantVar.ip+"/verification/getCaf", 
           postParameters); 
      } catch (Exception e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

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

      if (jsonStr != null) { 
       try { 
        JSONObject jsonObj = new JSONObject(jsonStr); 

        // Getting JSON Array node 
        contacts = jsonObj.getJSONArray("data"); 


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

         String id = c.getString(TAG_ID); 
         String name = c.getString(TAG_NAME); 
         String address = c.getString(TAG_ADDRESS); 
         String status = c.getString(TAG_STATUS); 
         String varType = c.getString(TAG_VARTYPE); 


         HashMap<String, String> contact = new HashMap<String, String>(); 

         // adding each child node to HashMap key => value 
         contact.put(TAG_ID, id); 
         contact.put(TAG_NAME, name); 
         contact.put(TAG_ADDRESS, address); 
         contact.put(TAG_STATUS, status); 
         contact.put(TAG_VARTYPE, varType); 
         contact.put("priority", priority); 

         // adding contact to contact list 
         contactList.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(GetLead.this, contactList, R.layout.list_item, new String[]{TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_VARTYPE, priority}, new int[]{R.id.custId, 
        R.id.name, R.id.address, R.id.verificationType}); 
      if (priority.equals("high")) { 
       setListAdapter(adapter); 
       LinearLayout listLayout = (LinearLayout)findViewById(R.id.list_layout); 
       listLayout.setBackgroundColor(Color.GREEN); 

      } 

     } 

    } 

을 정의? onPostExecute()

@Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 

     final ListAdapter adapter = new SimpleAdapter(GetLead.this, contactList, R.layout.list_item, new String[]{TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_VARTYPE, priority}, new int[]{R.id.custId, 
       R.id.name, R.id.address, R.id.verificationType}); 

     if (priority.equals("high")) { 
      GetLead.this.runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        setListAdapter(adapter); 
        getListView().setBackgroundColor(getResources().getColor(R.color.colorAccent)); 
       } 
      }); 
     } 
    } 
+0

실제 목록 객체 자체가 아니라 데이터를 표현/처리하는 객체에서'setBackgroundColor()'를 시도하기 때문에 코드가 작동하지 않는 이유가 있습니다. 레이아웃에서 실제'ListView' 인스턴스를 가져 와서 그 객체에서'setBackgroundColor()'를 호출해야합니다. 'ListAdapter'는'ListView'와 같은 것이 아닙니다. –

+0

맞춤 어댑터 클래스 마녀가 자신 만의 레이아웃을 부 풀리게 만들고이 어댑터 클래스에서 레이아웃의 상위 뷰 배경색을 설정하려면 우선 순위가 "높음"인지 확인해야합니다. 이 대답을 확인하십시오 : http://stackoverflow.com/a/8166802/5519005 –

답변

0

업데이트 : 당신이 원하는대로

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    if (convertView == null) { 
     convertView = inflater.inflate(R.layout.custom_event_row_view, parent, false); 
     convertView.setBackgroundColor(Color.RED); 

지금 당신은 각 항목의 색상을 설정할 수 있습니다.

+0

정적 인 컨텍스트에서 setBackgroundColor (int)를 참조 할 수 없습니다. listView.setBackgroundColor (R.color.blue)를 사용할 때이 오류를 표시합니다. 나는 이것을 방지하기 위해 여기에 – AARUSH

+0

복사본을 코드에 붙여 넣습니다. –

+0

나는 이미 코드 – AARUSH

0

의 코드 당신은, 어댑터에서이 작업을 수행 같은 getView를 오버라이드 (override) 할 필요가

+0

작동하지 않습니다. 나는 내 코드를 업데이트하고 선생님을 도왔습니다 .... findviewByid에 정의 된 "listItem"은 코드에 – AARUSH

0

실제로 xml에 사용 된 레이아웃 배경색을 설정하여 색상을 설정해야합니다.

if (priority.equals("high")) { 
LinearLayout listLayout = listItem.findViewByid(R.id.list_layout); 
    listLayout.setBackground(R.color.Red) 
       setListAdapter(adapter); 
      } 
+0

입니다. – AARUSH

관련 문제