1

How can I find an object (for example Imageview) in the Mainactivity from another class that this class have extends?

my Mainactivity :

public class MainActivity extends Activity implements OnClickListener {

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

@Override
public void onClick(View view){

}}

my DrawingView class:

    public class DrawingView extends View {

    public DrawingView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        drawCanvas = new Canvas(canvasBitmap);
    }

    ............

}

in my activity_main.xml I have an Imageview, but i cant find it. I searched in site and best answer is like this:

How to update a TextView of an activity from another class

but this answer dose not help me. how can I find Imageview in onTouchEvent or others part of DrawingView class? and why this cod dos not work for me:

imageView = (ImageView) getRootView().findViewById(R.id.imageView); 
Community
  • 1
  • 1
joojoo
  • 11
  • 2

2 Answers2

0

You can pass a reference of your Activity/Context/widgets (better, create a WeakReference) to your DrawingView class, but this way your class becomes tightly coupled with your Activity, and that's not a good practice.

The best way is in the second answer that you have linked. Declare an interface in the DrawingView class and let the Activity implement the interface. You call a method of this interface in DrawingView class when you need it, and in the corresponding implementation in your Activity you have all the references that you need: https://stackoverflow.com/a/27939196/3333165

Community
  • 1
  • 1
iClaude
  • 163
  • 1
  • 9
0

thanks for your post. but when I change my DrawingView class to down Code my app to be closed by this massage "unfortunately Drawing has stopped"

my new DrawingView class:

public class DrawingView extends View {

//public DrawingView(Context context, AttributeSet attrs) {
//    super(context, attrs);
//}

Context context;
public DrawingView(Context context, AttributeSet attrs){
    super(context, attrs);
    this.context=context;
}

public void Update(){
    imageView = (ImageView) ((Activity)context).findViewById(R.id.imageView);
    imageView.setVisibility(GONE);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    drawCanvas = new Canvas(canvasBitmap);
}

............
}
joojoo
  • 11
  • 2