我试图用我正在计算的另一个片段中的值在片段中绘制一个图。另一个片段正在更改类中的静态变量(AnalysedTweet),在片段中使用这些变量绘制图形。
有办法更新图表吗?(用上面的图表更新片段)
这是图片段的代码:
public class Statistics extends Fragment {
GraphicalView mChartView= null;
private DefaultRenderer mRenderer = new DefaultRenderer();
private CategorySeries mSeries = new CategorySeries("Sentiment");
private int[] COLORS = new int[] {Color.parseColor("#009900"),Color.RED, Color.GRAY};
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.activity_statistics, container, false);
int[] count = new int[3];
count[0] = AnalysedTweet.getCount_pos();
count[1] = AnalysedTweet.getCount_neg();
count[2] = AnalysedTweet.getCount_obj();
String[] categoryNames = {"Positive","Negative","Objective" };
for(int i=0;i<3;i++){
mSeries.add(categoryNames[i], count[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[i]);
renderer.setDisplayChartValues(true);
mRenderer.addSeriesRenderer(renderer);
}
mChartView = ChartFactory.getPieChartView(this.getActivity(), mSeries, mRenderer);
Log.i("CHART", Integer.toString(mSeries.getItemCount()));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
mChartView.setLayoutParams(params);
RelativeLayout layout = (RelativeLayout) rootView.findViewById(R.id.chartsRelativeLayout);
layout.addView(mChartView);
return rootView;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}发布于 2014-04-25 07:17:55
首先,您不应该在交流中使用静态变量(也称为全局变量),这是非常糟糕的做法。这就是谷歌在这件事上的建议:
通常,您希望一个片段与另一个片段进行通信,例如根据用户事件更改内容。所有片段到片段的通信都是通过相关的活动完成的。两个片段不应该直接交流。为了允许片段与其活动进行通信,您可以在片段类中定义一个接口并在活动中实现它。片段在其onAttach()生命周期方法中捕获接口实现,然后调用接口方法以便与活动通信。 下面是片段到活动通信的示例:
公共类HeadlinesFragment扩展了ListFragment { OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}参见更多的heree http://developer.android.com/training/basics/fragments/communicating.html
https://stackoverflow.com/questions/23280209
复制相似问题