将新对象附加到活动

时间:2018-02-15 08:29:47

标签: android android-layout android-constraintlayout

每当Switch处于On状态时,我一直试图在现有textview(注意开关位于活动顶部)的新textview上插入当前时间,活动的相关对象描述如下: 活动ID:stpclk

现有的textview id:lstview

以下代码在模拟器中停止了应用,我尝试过更改 final ConstraintLayout constraintLayout =(ConstraintLayout)findViewById(R.id.stpclk); 与

final ConstraintLayout constraintLayout = new ConstraintLayout(this); 

以下更改有效但我的previos布局(切换和以前的textview) 不保留,我的目标是保留时间和现有的布局对象

有人可以帮助我,我是Android编程新手吗?

 protected void onCreate(Bundle savedInstanceState) {
    final Switch mySwitch=(Switch)findViewById(R.id.toggleid);
    final TextView txtview2= (TextView)findViewById(R.id.lstview);
    final Switch mySwitch=(Switch)findViewById(R.id.toggleid);
    final ConstraintLayout constraintLayout = (ConstraintLayout)findViewById(R.id.stpclk);

            mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // do something, the isChecked will be
                    if(mySwitch.isChecked()){
                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                        curr_time[0] = sdf.format(new Date());

                    }
                    else{
                        TextView ctime = new TextView(StopClock.this);
                        ctime.setText(curr_time[0]);
                        ctime.setTextSize(25);
                        ctime.setId(View.generateViewId());

                        ConstraintLayout.LayoutParams clpcontactUs = new ConstraintLayout.LayoutParams(
                                ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
                        ctime.setLayoutParams(clpcontactUs);

                        constraintLayout.addView(ctime);

                        ConstraintSet constraintSet = new ConstraintSet();
                        constraintSet.clone(constraintLayout);
                        constraintSet.connect(ctime.getId(),ConstraintSet.TOP,txtview2.getId(),ConstraintSet.BOTTOM,18);
                        constraintSet.connect(ctime.getId(),ConstraintSet.LEFT,txtview2.getId(),ConstraintSet.LEFT,18);
                        constraintSet.connect(ctime.getId(), ConstraintSet.RIGHT, txtview2.getId(), ConstraintSet.RIGHT, 18);

                        constraintSet.applyTo(constraintLayout);
                        constraintLayout.setId(R.id.stopclkid);
                        setContentView(constraintLayout);

                    }
                    // true if the switch is in the On position
                }

            });
    }

0 个答案:

没有答案