Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android:Wrong onMeasure - Many calls

I hope for the help. My problem with function call onMeasure. In My xml a file(RelativeLayput) - 3 elements:TextView, RelativeLayout and include them my class. Now my Main Activity class and my create class

  public class MainActivity extends Activity implements OnTouchListener {

    final String LOG_TAG = "myLogs";
    TextView tv1;
UiMyClass uimc;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv1 = (TextView) findViewById(R.id.mytext2);
    tv1.setOnTouchListener(this);
    String str1 = "qwertyy";
    uimc = (UiMyClass) findViewById(R.id.myclass1);
    Log.d(LOG_TAG, "Open1-0" + "   " + str1);       
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    int evX = (int) event.getX();
    int evY = (int) event.getY();
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        tv1.setText("uyq8qyw");
        break;
    case MotionEvent.ACTION_MOVE:
        break;
    case MotionEvent.ACTION_UP:
        break;
    }
    Log.d(LOG_TAG, "Touch_GS");
    return true;
}
}

public class UiMyClass extends View {

final String LOG_TAG = "myLogs";

public UiMyClass(Context context, AttributeSet attrs) {
    super(context, attrs);      
    this.setBackgroundResource(R.drawable.ic_launcher);
    Log.d(LOG_TAG, "Initialization_00");        
}

@Override 
protected void onMeasure(int x, int y) {
    setMeasuredDimension(100, 50);
    Log.d(LOG_TAG, "Measure_02");       
}

}

Problem here in what. When the application is started, is fulfilled onMeasure, but why that 8 times (it is visible on logs). By the way, if to increase an enclosure of my element View in other layers, onMeasure it is carried out 2 ^ (quantity of the enclosed layers + 2) time. (I.e. for one 8, for 2 - 16) Further when I press the TextView event onTouch is carried out, but thus also it is started onMeasure. How to make so that start onMeasure any more was not and, in general, it was started only once. In advance I thank for the help.

like image 925
zharik86 Avatar asked Dec 16 '22 12:12

zharik86


1 Answers

This kind of behavior happens in two situations: - When you use a LinearLayout and set layout_weight on one of the children. The weight attribute causes that child to be measured twice. So if you put another LinearLayout with a weight inside you'll get 4 measures for the leaf child. - The same happens can happen with RelativeLayout. Some constraints can cause multiple measure passes.

This means you should be careful with the weight attributes and RelativeLayout. I recommend you use Android's traceview profiler and Hierarchy Viewer to measure the performance of your layouts.

like image 76
Romain Guy Avatar answered Dec 30 '22 07:12

Romain Guy