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>