How to lay out Views in RelativeLayout programmatically?

前端 未结 9 1769
心在旅途
心在旅途 2020-11-22 15:04

I\'m trying to achieve the following programmatically (rather than declaratively via XML):


   

        
9条回答
  •  天涯浪人
    2020-11-22 15:40

    Android 22 minimal runnable example

    Source:

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    
    public class Main extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            final RelativeLayout relativeLayout = new RelativeLayout(this);
    
            final TextView tv1;
            tv1 = new TextView(this);
            tv1.setText("tv1");
            // Setting an ID is mandatory.
            tv1.setId(View.generateViewId());
            relativeLayout.addView(tv1);
    
            // tv2.
            final TextView tv2;
            tv2 = new TextView(this);
            tv2.setText("tv2");
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.FILL_PARENT);
            lp.addRule(RelativeLayout.BELOW, tv1.getId());
            relativeLayout.addView(tv2, lp);
    
            // tv3.
            final TextView tv3;
            tv3 = new TextView(this);
            tv3.setText("tv3");
            RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            );
            lp2.addRule(RelativeLayout.BELOW, tv2.getId());
            relativeLayout.addView(tv3, lp2);
    
            this.setContentView(relativeLayout);
        }
    }
    

    Works with the default project generated by android create project .... GitHub repository with minimal build code.

提交回复
热议问题