如何使用java在android中设置列表视图的背景颜色

时间:2016-07-19 10:41:17

标签: java android

我想用java设置listview的背景颜色... 下面是我想要设置列表视图的背景颜色的代码 名称,地址,varificationtype中的值来自服务器。 现在我想将listview的背景颜色设置为RED 我已经定义了

 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);

            }

        }

    }

我如何才能在这里使用Java?

3 个答案:

答案 0 :(得分:0)

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));
                }
            });
        }
    }

答案 1 :(得分:0)

您应该在适配器中执行此操作,覆盖getView,如下所示:

@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);

现在您可以根据需要设置每个条目的颜色。

答案 2 :(得分:0)

实际上,您必须设置xml中使用的布局背景颜色以相应地设置颜色。

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