0

我创建了一个片段,它使用接收器接收数据并在视图上动态呈现(@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);
            }
            }
        });
    }
}
4

2 回答 2

0

LinearLayout在添加新按钮之前从您的旧按钮中删除。您可以使用removeAllViews()方法:

main_layer.removeAllViews(); // to remove the old Buttons
for(int i=0;i<resultValue.size();i++){// then you can loop to add the new ones
     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);
     main_layer.addView(button1);
}
于 2016-01-11T19:55:20.820 回答
0

答案是,为变量赋值并不意味着您重新创建了一个已经在屏幕上绘制的视图。首先,尝试删除已添加的按钮main_layer.removeView(button1),然后创建并添加一个新按钮

于 2016-01-11T19:56:53.397 回答