I'm still new in java and android studio. I want to know if there is a way to access a layout in another activity.
What I want is to be able to change the background image of my main activity through a different activity. So my main activity has a button that will direct them to a new activity, and that new activity has some buttons that will customize the background image of the main activity. (basically press a button and the background will change).
In my main.xml I got my constraint layout. How do I access that constraint layout in a different java class?
I think you can't do that. What you need is to pass some data to an activity you want to customize from your costomization activity with intent. The other way - you can use fragments, for example DialogFragment which is just attached to your mainactivity, so you can change it
@cupcake, You can access the object but you have to create the object name as static. and call from NewActivity But your view might be null if you dont call findViewbyId: Here and example : MainAcitvity
static TextView mTextViewTv;
static ConstraintLayout mLayoutCl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewTv = findViewById(R.id.helloWorldTv);
mLayoutCl =findViewById(R.id.mLayout);
mTextViewTv.setOnClickListener(v -> startNewActivity());
}
private void startNewActivity() {
startActivity(new Intent(MainActivity.this,NewActivity.class));
}
NewActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
//you can call in on click, **Becareful with NUll expection**
//this is just example
MainActivity.mLayoutCl.setBackgroundColor(getResources().getColor(R.color.black));
}
This type of method NOT RECOMMEND
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.