我创建了一个片段,它使用接收器接收数据并在视图上动态呈现(@runtime)。但是,每次接收器获取新数据时,都会创建按钮并且视图不会被覆盖,而是使用前一个按钮添加。主要问题在于 Fragment 类,因为我已经测试了 TextViews。帮我找出这个片段的问题:
public class OneFragment extends Fragment{
SDReceiver sdr;
View v;
TextView tx;
LinearLayout main_layer;
public OneFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_one, container, false);
tx = (TextView) v.findViewById(R.id.result);
main_layer = (LinearLayout) v.findViewById(R.id.dynamic_layout);
setupServiceReceiver();
onStartService();
return v;
}
public void onStartService(){
Intent intent = new Intent(getActivity(),ServiceHandler.class);
intent.putExtra("receiver",sdr);
getActivity().startService(intent);
}
public void setupServiceReceiver() {
// Setup GUI by accessing objects from ArrayList
sdr = new SDReceiver(new Handler());
sdr.setReceiver(new SDReceiver.Receiver() {
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == Activity.RESULT_OK) {
try{
HashMap<Integer,String[]> resultValue = (HashMap<Integer,String[]>) resultData.getSerializable("itemList");
for(int i=0;i<resultValue.size();i++){
String data[] = resultValue.get(i);
String resultString = data[1] + ", " + data[2] + ", " + data[3] + ", " + data[4] + "\n";
Button button1 = new Button(v.getContext());
button1.setId(i);
button1.setText(resultString);
//button1.setOnClickListener(getOnClickDoSomething(button1));
main_layer.addView(button1);
//tx.setText(bee);
}
}catch(NullPointerException e){
e.printStackTrace();
}
//tx.setText(values);
}
}
});
}
}