Suppose the class inherited from the Activity in the markup is an ImageView . And it is required from another class, to this ImageView to assign an image from resources. By what methods will you do it? Please provide a piece of this code. If the ImageView is found by the findViewById(...) method, then by accessing this found object, through an instance of the class, we get the Null object, although in the class itself, where it was found, it is naturally not Null. So how to properly access objects of another class. Using the setter method also gives no results.

 public class MainActivity extends AppCompatActivity implements SomeClass.MyInterface { private ImageView mImageView; //SomeClass someClass; @Override public void setImage(){ mImageView.setImageResource(R.mipmap.ic_launcher); } @Override public void onCreate(Bundle b){ super.onCreate(b); setContentView(R.layout.activity_main); mImageView = (ImageView) findViewById(R.id.imageView); SomeClass someClass = (SomeClass) findViewById(R.id.surface); //т.к. активити реализует интерфейс, то в класс, сеттером, передаём её someClass.setInterface(this); //теперь вызывая метод интерфейса setImage будет вызван метод в актвити. } } 

.

 public class SomeClass extends SurfaceView { private MyInterface mMyInterface; public SomeClass(Context context, AttributeSet attributeSet) { super(context, attributeSet); mMyInterface.setImage(); } public interface MyInterface{ void setImage(); } public void setInterface(MyInterface myInterface){ mMyInterface = myInterface; } //далее где-то в классе (в к-л методе) вызываем метод setImage так: //mMyInterface.setImage(); } 

.

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="example.myapplicationzzz.MainActivity"> <view class="example.myapplicationzzz.SomeClass" android:id="@+id/surface" android:layout_width="match_parent" android:layout_height="match_parent"> </view> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="55dp" android:layout_marginStart="55dp" android:layout_marginTop="30dp" android:id="@+id/imageView" /> </RelativeLayout> 

    1 answer 1

    How long are you suffering ...

    A class must contain an interface in its field and have a setter to it:

     public class SomeClass { public interface MyInterface{ void setImage(); } private MyInterface mMyInterface; public void setInterface(MyInterface myInterface){ mMyInterface = myInterface; } //далее где-то в классе (в к-л методе) вызываем метод setImage так: //mMyInterface.setImage(); } 

    Aktviti must implement an interface defined in another class.

     public class MainActivity extends AppCompatActivity implements MyInterface{ private ImageView mImageView; @Override public void setImage(){ mImageView.setImageResource(R.mipmap.ic_launcher); //если надо запускать в основном потоке, //т.е. этот метод был вызван не из основного //и происходит падение из-за обращения к разметке //не из основного потока, то надо делать так: //runOnUiThread(new Runnable(){ //public void run(){ //mImageView.setImageResource(R.mipmap.ic_launcher); //} //}); } @Override public void onCreate(Bundle b){ super.onCreate(b); setContentView(R.layout.activity_main); mImageView = findViewById(/*тут id из разметки*/); SomeClass someClass = new SomeClass(); //т.к. активити реализует интерфейс, то в класс, сеттером, передаём её someClass.setInterface(this); //теперь вызывая метод интерфейса setImage будет вызван метод в актвити. } } 
    • Why can't I just pass the MainActivity to the MainActivity class and call activity.setImage() ? I think your way is a bit overloaded. - Mansur Nashaev
    • In principle, it is not necessary to even transfer the whole Activity ; you can use the ImageView itself. - Mansur Nashaev
    • one
      @Turalllb, you call mMyInterface.setImage(); in the constructor, i.e. before calling setInterface() - it’s natural that you have mMyInterface null . You need to call the interface method no earlier than you pass it to the view. \ - YuriiSPb
    • one
      You are not from the main thread. Try to wrap in ruOnUiThread - JuriySPb
    • one
      @Turalllb, added a response with the code to run in the main thread. And Mansur Nashaev meant that you can do the same thing without interfaces, transferring, instead of activating it, or even just an ImageView. It would have worked, but this is a bad approach, because logic must be separated and for good one view should not be aware of the existence of the other and interact with it directly. If the code is not having this in mind, then the code over time turns into a mess and a small change in one place breaks everything and everywhere and even unpredictable. Well, the reuse of the code becomes impossible. - Yuriy SPb