活动之间的数据

时间:2015-09-21 16:51:28

标签: java android

我有一个特殊的类,我的ListView的自定义适配器,我需要从另一个Activity获取一些数据。但是我对方法GetIntent()GetExtras()的实现不起作用。有什么问题?

这是我的自定义适配器代码:

public class CustomAdapter extends ArrayAdapter<String> {
    int myColor,myWidth;
    private final Context context;
    private final String[] values;

    public CustomAdapter(Context context, String[] values) {
        super(context, R.layout.list_item, values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //  return super.getView(position, convertView, parent);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.list_item, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.ColorTextButton);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.imageViewIcon);
        TextView textView1 = (TextView) rowView.findViewById(R.id.HelpButton);
        textView.setText(values[position]);

        String s = values[position];
        System.out.println(s);
        if (s.equals("Monday")) {
            imageView.setImageResource(R.drawable.arrow2);
            textView.setBackgroundColor(Color.YELLOW);
        } else if (s.equals("Wednesday")) {
            imageView.setImageResource(R.drawable.arrow2);
            textView1.setBackgroundColor(Color.GREEN);
        } else if (s.equals("Friday")) {
            imageView.setImageResource(R.drawable.arrow2);
        } else {
            imageView.setImageResource(R.drawable.arrow);
        }
        return rowView;
    }
}

1 个答案:

答案 0 :(得分:0)

如果您希望数据可访问从一些活动中您应该考虑使用单例数据类。因此,不是试图将数据从适配器传递到第二个活动,而adaper和Activity都使用相同的方法来获取数据类

 public class DataProvider {
 private static DataProvider instance;


    public static DataProvider getInstance()
    {
       if(null == instance){instance = new DataProvider();}
       return instnace;
    }

    public String[] getObjects(){
        return this.myStringArray;
    }

    // add more methods in here to retrieve and count your data as you need
 }

然后在你的活动中你可以

// somewhere
myStingArrayInMyActivity = DataProvider.getInstance().getObjects()

也在你的适配器中 你可以做到

public class CustomAdapter extends ArrayAdapter<String> {
int myColor,myWidth;
private final Context context;
private final String[] values;

public CustomAdapter(Context context, String[] values) {
  super(context, R.layout.list_item, values);
  this.context = context;
  this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
 // your code
textView.setText(DataProvider.getInstance.getObjects[position]);

String s = DataProvider.getInstance.getObjects[position];
/// your code
 return rowView;
  }
 }