dynamically add remove control form linearlayout

后端 未结 4 2028
一个人的身影
一个人的身影 2021-01-05 11:15

I have 3 layouts, I need when click on button access certain layout and ad remove controls from and in it any idea how to achieve that , this is the code I use



        
相关标签:
4条回答
  • 2021-01-05 11:45

    Remove view from parent on Android:

    View myView = findViewById(R.id.my_view);
    ViewGroup parent = (ViewGroup) myView.getParent();
    parent.removeView(myView);
    

    Android remove all child views:

    LinearLayout formLayout = (LinearLayout)findViewById(R.id.formLayout);
    formLayout.removeAllViews();
    

    Add view to parent on Android:

    Button myButton = new Button(getApplicationContext());
    myButton.setLayoutParameters(new LinearLayout.LayoutParams(
                                         LinearLayout.LayoutParams.FILL_PARENT,
                                         LinearLayout.LayoutParams.FILL_PARENT));
    
    myLayout.addView(myButton);
    

    you can use:

    LinearLayout.LayoutParams.FILL_PARENT
    

    or

    LinearLayout.LayoutParams.WRAP_CONTENT
    
    0 讨论(0)
  • 2021-01-05 12:01

    Look at the setVisibility method of the View class. It allows you to make Views appear or disappear from the UI very simply.

    In your button's click listener just add view.setVisibility(View.GONE) to make any layout or widget go away. You can make it reappear by calling view.setVisibility(View.VISIBLE)

    0 讨论(0)
  • 2021-01-05 12:03

    Sample for dynamically add or remove a view:

    TextView tv = new TextView(this);
    
            tv.setWidth(LayoutParams.WRAP_CONTENT);
    
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.RIGHT;
            tv.setLayoutParams(params);
            tv.setTextAppearance(this, R.style.darkTextNormal);
            tv.setBackgroundResource(R.color.lightBlue);
            tv.setTextSize(16);
    
    yourLinearLayout.addView(tv);
    

    // or

    yourLinearLayout.removeView(tv);
    
    0 讨论(0)
  • 2021-01-05 12:08

    Add andoird:id="@+id/linerlayout_1" after that you can access this view easy inside the code with the findviewbyid() method.

    For examlpe: place this inside the button's onclicklistener method.

    LinearLayout ll = (LinearLayout) findViewById(R.id.linerlayout);
    ll.setVisibility(View.GONE); // this row will hide the entire linerlayout
    ll.addView(someView); //this row will add the specified View f.e.: TextView
    ll.removeView(otherView); // this row will remove the view
    

    And you can manage th view visibility by xml attribute android:visibility too.

    0 讨论(0)
提交回复
热议问题