Android Fragment FragmentStatePagerAdapter更改TextView的backroundcolor但仅更改onCreate

时间:2015-07-06 11:13:47

标签: android android-fragments

因为我是Android类型的新手,所以我希望你能帮我一把:

该应用程序使用由FragmentManager管理的不同片段。这个类由FragmentStatePagerAdapter扩展。

如果我使用这个特定的片段:

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by welser on 22.06.2015.
 */
public class RalisierungsFragment extends ListFragment {
    // Store instance variables
    private String title;
    private int page;
    public int value = 111;
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_DATUM = "created_at";
    static int [] colors = new int[] {0xF0FFFF, 0xD3D3D3 };
    // Hashmap for ListView
    ArrayList<HashMap<String, String>>productsList = new ArrayList<HashMap<String, String>>();
    // Progress Dialog
    private ProgressDialog pDialog;
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    // url to get all products list
    //private static String url_all_products = "http://novaten.cloud.hs-furtwangen.de/phpandroid/get_all_products.php";
    private static String url_all_products = "http://141.28.100.152/phpandroid/get_all_products.php";
    // products JSONArray
    JSONArray products = null;
    public TextView text;

    // newInstance constructor for creating fragment with arguments
    public static RalisierungsFragment newInstance(int page, String title) {
        RalisierungsFragment rs = new RalisierungsFragment();
        Bundle args = new Bundle();
        args.putInt("someInt", page);
        args.putString("someTitle", title);
        rs.setArguments(args);
        return rs;
    }

    // Store instance variables based on arguments passed
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = getArguments().getInt("someInt", 0);
        title = getArguments().getString("someTitle");
        text = (TextView) getActivity().findViewById(R.id.name);
        // Loading products in Background Thread
        new LoadAllProducts().execute();

    }
    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity()); // abgendert
            pDialog.setMessage("Loading data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
         public String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ",value + "");

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        String price = c.getString(TAG_PRICE);
                        String date = c.getString(TAG_DATUM);
                        String description = c.getString(TAG_DESCRIPTION);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_DATUM, date);
                        map.put(TAG_PRICE, price);
                        map.put(TAG_DESCRIPTION, description);
                        set(products.length());
                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */

                    ListAdapter adapter = new SimpleAdapter(
                            getActivity(), productsList,
                            R.layout.list_item, new String[]{TAG_PID,
                            TAG_NAME, TAG_PRICE, TAG_DATUM,TAG_DESCRIPTION},
                            new int[]{R.id.pid, R.id.name, R.id.price, R.id.datum, R.id.description});
                            //text.setBackgroundColor(Color.GREEN);


                            setListAdapter(adapter);
                }
            });



        }

        public void set(int i){
            value = i;
        }

    }

}

背景颜色应取决于listview上的每个json String(R.id.name)。我希望我尽可能清楚地描述一切。如果还有其他一些问题,请不要犹豫,以纠正我。 非常感谢你:))

2 个答案:

答案 0 :(得分:0)

要更改每一行的颜色,您必须使用自己的adater。

首先使用所需的行布局创建xml文件。然后在此骨架后创建自定义适配器:

public class YourAdapter extends BaseAdapter {

     private String[] mStrings;//the array to display
     private LayoutInflater mInflater;

     private YourAdapter(Context context, String[] datas) {
          mInflater = LayoutInflater.from(context);
          mStrings = datas;
    }

     @Override
     public int getCount() {
          return mStrings.length();
     }

     @Override
     public long getItemIdAtPosition(int position) {
          return position;
     }

     @Override
     public Object getItemAtPosition(int position) {
          return mStrings[position];
     }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
           //the following line is bad in terme of oprimization, you should use a holder, but it is a bit too long to write here, see the link below for example
           convertView = mInflater.inflate(R.layout.your_row);


           //set the datas and the colors to the row
           TextView textView =  (TextView) convertView.findViewById(R.id.your_text_view_id);
           textView.setText(mStrings[position]);
           convertView.setBackgroundColor(R.color.your_color);//you can change the color following the position or the string that you put in
           return convertView;
      }
}

最后在您的活动中使用

 YourAdapter adapter = new YourAdapter(this, productList);
 listView.setAdapter(adapter);

有关更详细的实施,请参阅http://www.vogella.com/tutorials/AndroidListView/article.html#adapterown

答案 1 :(得分:0)

谢谢大家。我决定简单地覆盖getView()Methode,所以我不需要额外的类。

 ListAdapter adapter = new SimpleAdapter(
                                    getActivity(), productsList,
                                    R.layout.list_item, new String[]{TAG_PID,
                                    TAG_NAME, TAG_PRICE, TAG_DATUM,TAG_DESCRIPTION},
                                         new int[]{R.id.pid, R.id.name, R.id.price, R.id.datum, R.id.description}){


                                @Override
                                public View getView (int position, View convertView, ViewGroup parent) {
                                    View view = super.getView(position, convertView, parent);
                                    if ("major".equals(productsList.get(position).get(TAG_NAME))){
                                        view.setBackgroundColor(Color.BLUE);
                                     } else if ("cirtical".equals(productsList.get(position).get(TAG_NAME))){
                                        view.setBackgroundColor(Color.RED);
                                     } else if ("warning".equals(productsList.get(position).get(TAG_NAME))) {
                                        view.setBackgroundColor(Color.RED);
                                    } else if ("info".equals(productsList.get(position).get(TAG_NAME))) {
                                        view.setBackgroundColor(Color.GREEN);
                                    } else {
                                        view.setBackgroundColor(Color.BLACK);
                                    }
                                    return view;
                                }
                            };
                   setListAdapter(adapter);