Baradwaj Aryasomayajula
Baradwaj Aryasomayajula

Reputation: 1204

How to get the height and width of a view?

How can I get the height and width of an view of a view (which belongs to another activity) in the current activity. For example. There is a button in aactivity one and I have to get the attributes of teh button in activity two with the help of its id. (I have considered view because it can be ImageView, TextView, WebView or anything).

Here I am pasting the code which I have tried.

public class SecAct extends 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();
}

}

I am able to get the value of a but I am not able to get the attribute of the v(View) i.e., height, width or id e.t.c. I am getting an null pointer exception.

Upvotes: 0

Views: 1033

Answers (3)

Andre Amaral Braga
Andre Amaral Braga

Reputation: 321

First get the context from the view's activity, for example:

public static Context con;

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

Then, at the another activity:

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);

Finally, get the width and height:

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

Maybe these values (width and height) can be 0, so you have to do it:

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

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

Upvotes: 1

amit singh
amit singh

Reputation: 1422

You are getting null pointer exception beacause you haven't initialized your ArrayList butList1. Initialize it and add items to it, then use it. Like this-

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

Upvotes: 0

Kunu
Kunu

Reputation: 5134

try getMeasuredHeight() method

Upvotes: 0

Related Questions