0

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.

Baradwaj Aryasomayajula
  • 1,184
  • 1
  • 16
  • 42

3 Answers3

1

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();
    }
});
Andre Amaral Braga
  • 321
  • 1
  • 7
  • 23
0

try getMeasuredHeight() method

Kunu
  • 5,078
  • 6
  • 33
  • 61
  • @Kuni yeah I tried that too but It is showing the null pointer exception. – Baradwaj Aryasomayajula Jan 17 '14 at 12:26
  • @BaradwajAryasomayajula Check a similar question [link](http://stackoverflow.com/questions/4142090/how-do-you-to-retrieve-dimensions-of-a-view-getheight-and-getwidth-always-r) It may help you to solve your problem – Kunu Jan 17 '14 at 12:27
0

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));
amit singh
  • 1,407
  • 2
  • 16
  • 25