【问题标题】:How to get the height and width of a view?如何获取视图的高度和宽度?
【发布时间】:2014-01-20 20:30:03
【问题描述】:

如何获取当前活动中某个视图(属于另一个活动)的高度和宽度。 例如。活动一中有一个按钮,我必须借助其 ID 获取活动二中按钮的属性。 (我考虑过视图,因为它可以是 ImageView、TextView、WebView 或任何东西)。

我在这里粘贴我尝试过的代码。

公共类 SecAct 扩展 Activity{

ArrayList<Integer> butList1;
RelativeLayout help;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_two);
    help = (RelativeLayout)findViewById(R.id.helplay);
    createWidgets();
}

private void createWidgets() {
    // TODO Auto-generated method stub
    butList1=MainActivity.butList;
    int a=butList1.get(0);
    View v=(View)(findViewById(a));
    int width=v.getWidth();
    int height=v.getHeight();
    help.addView(v);
    System.out.println("id is "+ width);
}

public void close(View v){
    finish();
}

}

我能够获得 a 的值,但我无法获得 v(View) 的属性,即高度、宽度或 id 等。我得到一个空指针异常。

【问题讨论】:

  • NPE 到底在哪里?行号??
  • 为什么你需要从上次活动中获取视图的高度??
  • View v 必须是 null。检查
  • System.out.println("id is "+ width);
  • 你能给我们看一下 Logcat 消息吗?

标签: android view width


【解决方案1】:

首先从视图的activity中获取上下文,例如:

public static Context con;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_one);
    con = this;
}

然后,在另一个活动中:

Context context = FIRST_ACTIVITY.con;
Activity firstActivy = (Activity) context;
ViewGroup firstActivityView = firstActivy.getWindow().getDecorView().findViewById(android.R.id.content);
View DISIRED_VIEW = firstActivityView.findViewById(R.id.DISIRED_VIEW_ID);

最后得到宽高:

int width = DISIRED_VIEW.getWidth();
int height = DISIRED_VIEW .getHeight();

也许这些值(宽度和高度)可以为0,所以你必须这样做:

final int width, height;
DISIRED_VIEW.post(new Runnable() {

    @Override
    public void run() {
        width = DISIRED_VIEW.getWidth();
        height = DISIRED_VIEW.getHeight();
    }
});

【讨论】:

    【解决方案2】:

    试试getMeasuredHeight()方法

    【讨论】:

    • @Kuni 是的,我也试过了,但它显示空指针异常。
    • @BaradwajAryasomayajula 检查类似问题link 它可能会帮助您解决问题
    【解决方案3】:

    您收到空指针异常,因为您尚未初始化 ArrayList butList1。初始化它并向其中添加项目,然后使用它。像这样-

    butList1 = new ArrayList<Integer>();
    butList1.add(findviewById(R.id.button_id));
    

    【讨论】:

    • 我想没有必要初始化 butList1 以及我在 createwidgets() 函数中初始化它的任何方式。所以我认为这不是错误。
    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多