【问题标题】:Programatically add buttons with different properties for different orientations以编程方式为不同方向添加具有不同属性的按钮
【发布时间】:2013-07-08 10:44:34
【问题描述】:

我需要在运行时向我的应用程序添加一个按钮,但我想根据方向设置不同的布局。对于纵向我希望宽度为wrap_content,但在横向我需要设置一个固定宽度。我知道如何单独执行这些操作,但我找不到任何方法让它们以与在 XML 布局文件中处理它的方式相同的方式工作。有可能吗?

【问题讨论】:

    标签: android orientation screen-orientation android-button


    【解决方案1】:

    我会检查手机方向

    getResources().getConfiguration().orientation
    

    并在引用中动态添加按钮

    Dev

    【讨论】:

      【解决方案2】:

      您首先需要一个 Display 实例:

      Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
      

      那么方向可以这样调用:

      int orientation = display.getOrientation();
      

      然后你可以创建不同的布局,

      public void onConfigurationChanged(Configuration newConfig) {
          super.onConfigurationChanged(newConfig);
          Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
          int orientation = display.getOrientation(); 
          switch(orientation) {
              case Configuration.ORIENTATION_PORTRAIT:
                  // ToDo layout for portrait
                  break;
              case Configuration.ORIENTATION_LANDSCAPE:
                  // ToDo layout for landscape
                  break;
          }
      }
      

      如果你想在运行时设置方向然后使用,

      setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT | ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
      

      创建一个类似的布局

              LinearLayout ll = new LinearLayout(this);
              ll.setOrientation(android.widget.LinearLayout.VERTICAL);
              ll.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
              // ARGB: Opaque Red
              ll.setBackgroundColor(0x88ff0000);
      
              TextView tv = new TextView(this);
              tv.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
              tv.setText("sample text goes here");
              // ARGB: Opaque Green
              tv.setBackgroundColor(0x5500ff00);
              ll.addView(tv);
      
              EditText et = new EditText(this);
              et.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
              et.setText("edit me please");
              // ARGB: Solid Blue
              et.setBackgroundColor(0xff0000ff);
              ll.addView(et);
      
              Button btn = new Button(this);
              btn.setText("Go!");
              btn.setOnClickListener(new Button.OnClickListener() {
                  public void onClick(View v) {
                      tv.setText(et.getText().toString());
                  }
              });
      
              ll.addView(btn);
              setContentView(ll);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-04
        • 2015-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多