如何从Json结果着色textview

时间:2016-10-19 08:14:53

标签: android json

我想从Json结果(下面的代码)设置颜色文本视图,如果statusspp是SPP textcolor是Red,如果statusspp是SP2D textcolor是Green。你能救我吗?

这是我的完整代码: 适配器类

public class AdapterSpp extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataSpp> data= Collections.emptyList();
    DataSpp current;
    int currentPos=0;

    public AdapterSpp(Context context, List<DataSpp> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.container_spp, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        MyHolder myHolder= (MyHolder) holder;
        DataSpp current=data.get(position);
        myHolder.textSppName.setText(current.getTextSppName());
        myHolder.textType.setText(current.getTextType());
        myHolder.textSize.setText("Uraian : " + current.getTextSize());
        myHolder.textPrice.setText("Rp. " + current.getTextPrice());
        myHolder.textTgl.setText("Tgl.SPP : " + current.getTextTgl());
        myHolder.textPrice.setTextColor(ContextCompat.getColor(context, android.R.color.holo_red_light));
        if(current.getTextType().equalsIgnoreCase("SPP")){
            myHolder.textType.setTextColor(android.R.color.holo_red_light);
        } else if(current.getTextType().equalsIgnoreCase("SP2D")){
            myHolder.textType.setTextColor(android.R.color.holo_blue_light);
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }


    class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView textSppName;
        TextView textSize;
        TextView textType;
        TextView textPrice;
        TextView textTgl;

        public MyHolder(View itemView) {
            super(itemView);
            textSppName = (TextView) itemView.findViewById(R.id.textFishName);
            textSize = (TextView) itemView.findViewById(R.id.textSize);
            textType = (TextView) itemView.findViewById(R.id.textType);
            textPrice = (TextView) itemView.findViewById(R.id.textPrice);
            textTgl = (TextView) itemView.findViewById(R.id.textTgl);

        }

        @Override
        public void onClick(View v) {

            Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();

        }

    }
}

这是我的主动课:

公共类MainActivity扩展了AppCompatActivity {

public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVSpp;
private AdapterSpp mAdapter;

SearchView searchView = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.search_main, menu);

    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

@Override
protected void onNewIntent(Intent intent) {

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery) {
        this.searchQuery = searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            url = new URL("http://ditkeu.unair.ac.id/andro/sp2d-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            conn.setDoInput(true);
            conn.setDoOutput(true);

            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            if (response_code == HttpURLConnection.HTTP_OK) {

                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                return (result.toString());

            } else {
                return ("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        pdLoading.dismiss();
        List<DataSpp> data = new ArrayList<>();

        pdLoading.dismiss();
        if (result.equals("no rows")) {
            Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        } else {

            try {


                JSONArray jArray = new JSONArray(result);

                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DecimalFormat formatter = new DecimalFormat("#,###,###");


                    DataSpp SppData = new DataSpp();
                    SppData.setTextSppName(json_data.getString("namapenerima"));
                    SppData.setTextSize(json_data.getString("uraianspp"));
                    SppData.setTextType(json_data.getString("statusspp"));
                    SppData.setTextPrice(formatter.format(json_data.getInt("jumlahtotal")));
                    SppData.setTextTgl(json_data.getString("tglsp2d"));
                    data.add(SppData);
                }

                mRVSpp = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterSpp(MainActivity.this, data);
                mRVSpp.setAdapter(mAdapter);
                mRVSpp.setLayoutManager(new LinearLayoutManager(MainActivity.this));

            } catch (JSONException e) {

                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}

我的自定义适配器:

public class DataSpp {

    private String textSppName;
    private String textSize;
    private String textType;
    private String textPrice;
    private String textTgl;

    //getters and setters
public String getTextSppName() {
    return textSppName;
}

public void setTextSppName(String textSppName) {
    this.textSppName = textSppName;
}

public String getTextSize() {
    return textSize;
}

public void setTextSize(String textSize) {
    this.textSize = textSize;
}

public String getTextType() {
    return textType;
}

public void setTextType(String textType) {
    this.textType = textType;
}

public String getTextPrice() {
    return textPrice;
}

public void setTextPrice(String textPrice) {
    this.textPrice = textPrice;
}

public String getTextTgl() {
    return textTgl;
}

public void setTextTgl(String textTgl) {
    this.textTgl = textTgl;
}

}

3 个答案:

答案 0 :(得分:0)

我假设您在 TextView

中显示文字
 TextView textView = (TextView)findViewById(R.id.your_textview);
    if(sppData.statusName.equalsIgnoreCase("SPP"))
    {textView.setTextColor(Color.RED)}
    elseif(sppData.statusName.equalsIgnoreCase("SP2D"))
    {textView.setTextColor(Color.GREEN)}

答案 1 :(得分:0)

你的适配器中的

尝试添加:

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

  MyHolder myHolder= (MyHolder) holder;
  DataSpp current=data.get(position);
  myHolder.textSppName.setText(current.SppName);
  myHolder.textSize.setText("Status : " + current.sizeName);
  myHolder.textType.setText("Uraian : " + current.catName);
  myHolder.textPrice.setText("Rp. " + current.price);
  myHolder.textTgl.setText("Tgl.SPP : " + current.tgl);
  myHolder.textPrice.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

  if(current.statusName.equalsIgnoreCase("SPP"))
  {
    myHolder.textType.setTextColor(Color.RED);
  } else if(current.statusName.equalsIgnoreCase("SP2D"))
  {
    myHolder.textType.setTextColor(Color.GREEN);
  }

}

答案 2 :(得分:0)

像这样创建一个模型类

public clas DataSpp{
  private String textSppName;
  private String textSize;
  private String textType;
  private String textPrice;
  private String textTgl;

 //getters and setters
  public String getTextSppName() {
    return textSppName;
  }

  public void setTextSppName(String textSppName) {
    this.textSppName = textSppName;
  }

  public String getTextSize() {
    return textSize;
  }

  public void setTextSize(String textSize) {
    this.textSize = textSize;
  }

  public String getTextType() {
    return textType;
  }

  public void setTextType(String textType) {
    this.textType = textType;
  }

  public String getTextPrice() {
    return textPrice;
  }

  public void setTextPrice(String textPrice) {
    this.textPrice = textPrice;
  }

  public String getTextTgl() {
    return textTgl;
  }

  public void setTextTgl(String textTgl) {
    this.textTgl = textTgl;
  }
}

在你的json回复中

DataSpp SppData = new DataSpp();
sppData.setTextSppName(json_data.getString("namapenerima");
sppData.setTextSize(json_data.getString("uraianspp");
sppData.setTextType(json_data.getString("statusspp");
sppData.setTextPrice(formatter.format(json_data.getInt("jumlahtotal")));
sppData.setTextTgl(json_data.getString("tglspp");

在设置值后的BindViewHolder中

if(current.textSppName.equalsIgnoreCase("SPP")){
    myHolder.textType.setTextColor(Color.RED);
} else if(current.textSppName.equalsIgnoreCase("SP2D")){
    myHolder.textType.setTextColor(Color.GREEN);
}