Backbutton to return to previous layout - java

Ok, say I have 1 Activity called MainActivity and 2 layouts linked to this actvity. In layout 1 i have a button which when clicked opens a webview in layout 2. How can I make it so when i press backbutton it goes back to layout 1 and doesnt exit the whole app.
Edit: fixed this by just creating another class and linking it to one of the layouts.

You have to override onBackPressed() in your activity and handle the logic there.
#Override
public void onBackPressed(){
if(/*layout2 visible*/){
// code here to go back to layout 1
}else{
super.onBackPressed();
}
}

I use this code using onBackPressed()
1- activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/go_to_second_layout"
android:text="Go to second layout"
android:onClick="onClick"/>
2- second_layout.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/second_layout">
3- MainActivity.java
public void onClick(View v){
switch(v.getId){
case R.id.go_to_second_layout:{
setContentView(R.layout.second_layout);
((LinearLayout)findViewById(R.id.second_layout)).setVisibility(View.VISIBLE);
break;}}}
#Override
public void onBackPressed() {
if (((LinearLayout)findViewById(R.id.second_layout)).VISIBLE==View.VISIBLE){
setContentView(R.layout.activity_main);
((LinearLayout)findViewById(R.id.second_layout)).setVisibility(View.GONE);
}
else {
super.onBackPressed();}
}

Related

The activities in android studio don't switch after pressing the button

I've already tried searching the Google on how to switch activities in android studio, even in the official documentation with tutorial. I did it exactly like it was said but I am still unable to get redirected to another activity after clicking a button.
I've entered an onClick name of the method to the button
it looks like this: https://i.imgur.com/pmsztaL.png (can't post images yet)
and this is my MainActivity.class file with said method
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void handleButtonAddNew(View view) {
MainActivity.this.startActivity(new Intent(MainActivity.this, AddItemActivity.class));
}
}
After pressing the button in a phone, the button does nothing.
This is my AddItemActivity.class
public class AddItemActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
}
public void handleButtonRemember(View view) {
finish();
}
}
How come the button doesn't work, what did I do wrong?
EDITS
EDIT: Successfully ran emulator and the buttons did in fact work, the problem lies within my phone, the buttons there don't want to work. Where could be the issue now?
EDIT: XML Layout of MainActivity.class
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/buttonAddNew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="188dp"
android:layout_marginRight="188dp"
android:layout_marginBottom="264dp"
android:text="#string/buttonAdd"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="395dp"
android:layout_height="715dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</android.support.constraint.ConstraintLayout>
EDIT: The problem was with scroll view blocking the clickable button so on my phone the button didn't register any clicks, after removing the scrollview the button works normally.
I'm afraid that this button doesn't get any listeners attached.
The programatic approach
From the Official Android Documentation
I'd suggest you use this in your onCreate callback:
Button button = (Button) findViewById(R.id.your_btn_id);
button.setOnClickListener((view) -> { theMethodYouWantToCallHere(view); });
XML approach
Please double check the following using this approach
Your activity is registered in the AndroidManifest.xml
You're including the android namespace to the XML file in the parent container of the layout file. IE: xmlns:android="http://schemas.android.com/apk/res/android"
Make sure you're setting the content view for the activity with setContentView(R.layout.your_layout_file);
Once 2 is satisfied make sure you're using the android namespace. IE: android:onClick="yourMethod"
As you're currently doing: Make sure the onClick callbacked method has the View view parameter; no more, no less
Make sure the onClick function is public in the activity.
And that no other clickable views are covering the view you're registering the onClick listener for :)
Including the namespace: xmlns:android="http://schemas.android.com/apk/res/android"
XML file
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:text="Click me!" android:onClick="clicked" android:layout_height="wrap_content" android:layout_width="wrap_content"/>
</FrameLayout>
The activity
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void clicked(View view){
Toast.makeText(this, "Hey! Im clicked!",Toast.LENGTH_SHORT).show();
}
}

Problem with button.setOnclickListener(this)

I started learning android, I'm trying to make a login activity but my buttons doesn't work for any reason.
I have implemented view.OnClickListener in my class
Here's my java code :
public class Login extends AppCompatActivity implements View.OnClickListener{
private Button btn_login, btn_reset;
private EditText et_username, et_pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.bt_login_login);
btn_login.setOnClickListener(this);
btn_reset = (Button) findViewById(R.id.bt_log_reset);
btn_reset.setOnClickListener(this);
et_username = (EditText) findViewById(R.id.et_log_username);
et_pwd = (EditText) findViewById(R.id.et_log_password);
}
#Override
public void onClick(View v) {
Log.w("test","test");
switch(v.getId()){
case R.id.bt_login_login :
DisplayData();
break;
case R.id.bt_log_reset :
resetData();
break;
}
}
I was wondering if this was not caused by the fact that my buttons are in a tree like this :
activity_login.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Login">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/txt_username"/>
<EditText
android:id="#+id/et_log_username"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/txt_login"/>
<EditText
android:id="#+id/et_log_password"
android:layout_width="match_parent"
android:inputType="textPassword"
android:hint="#string/pwd"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal|center_vertical"
>
<Button
android:id="#+id/bt_login_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/intro_login"/>
<Button
android:id="#+id/bt_log_reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/reset"/>
</LinearLayout>
</LinearLayout>
Ps : I may have a bad english, sorry for the inconvenience
make sure that your activity implements View.OnClickListener
everything else seems fine.
You can try a different approch. You can pass an anonymous class implementation of OnClickListener when using setOnClickListener.
Another way to do it is define an onClick attribute in the xml for each button, give it a functions name. You will have to have a function with the exact name in the activity for the function to be triggered (Android Studio will not let the project compile without a proper connection between them.)
The anonymous class implementation is prefered, as you will not be able to declare events in the xml all the time (when using fragments for example).
to implement an anonymous class in the setOnclickListener do this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//stuff to do when the button was clicked goes here.
}
});

Error as soon as I add setOnClickListener Android Studio

so for a school project I'm making an app, but I"m stuck.
I've got a button on my main class.
XML code of this class:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.larsb.csvvg.Home"
android:background="#drawable/home">
<Button
android:id="#+id/Lariks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button"
android:visibility="visible" />
<Button
android:id="#+id/Salland"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="45dp"
android:text="Button"
android:visibility="visible"
android:layout_alignTop="#+id/Lariks"
android:layout_alignLeft="#+id/Lariks"
android:layout_alignStart="#+id/Lariks" />
<Button
android:id="#+id/CSG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:visibility="visible"
android:layout_below="#+id/Salland"
android:layout_alignLeft="#+id/Salland"
android:layout_alignStart="#+id/Salland" />
</RelativeLayout>
So what I want to do is when I button click Lariks I switch to a new activity.
I try to do this with the following code:
public class MainActivity extends AppCompatActivity {
private static int WELCOME=4000;
Button lariks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lariks = (Button)findViewById(R.id.Lariks);
lariks.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent=new Intent(MainActivity.this,Home.class );
startActivity(intent);
finish();
}
},WELCOME);
}
}
In the public void onClick(view) thing I got the code for switching activity, that's not the problem.
The problem is that as soon as I add the:
lariks.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
the app can't launch anymore. It starts the emulator but it keeps saying the app has stopped. Anyone has any idea why this is? If I remove that part of the code the app actually does run.
Your Button with android:id="#+id/Lariks" is not in the activity_main layout (as evidenced by tools:context="com.example.larsb.csvvg.Home" and your crash). Therefore findViewById(R.id.Lariks) returns null, and attempting to call setOnClickListener() on this null reference causes a crash.
Your findViewById()-setOnClickListener() pair should likely be in the Home activity, or the button should be in the activity_main layout.

How to implement a back arrow in fragment

I have a nav drawer which in its first fragment i have a news page where the user clicks a button to see the whole news, and at that moment it enters another fragment.
I want to know how I implement an arrow to return to the previous fragment instead of the icon that opens the Navigation Drawer.
I've never worked with this before, I have no idea.
This is my Toolbar in MainActivity
appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
//toolbar title
toolbar.setTitle(null);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// Toolbar logo
logoToolbar = (ImageView) findViewById(R.id.logoToolbar);
logoToolbar.setImageResource(R.drawable.newstoolbar);
When the user click in "Read More" in the MainFragment
newsMore.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
newsFrag1 newsFragment1 = new newsFrag1();
ft.replace(R.id.fragment_container, newsFragment1);
ft.commit();
}
});
And then it goes to newsFrag1, which I want to have the back arrow
My Toolbar XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="studio.com.archeagemanager.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
app:elevation="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="?attr/colorPrimary"
android:gravity="center_vertical"
android:minHeight="56dp"
android:weightSum="1"
app:popupTheme="#style/AppTheme.PopupOverlay">
<ImageView
android:id="#+id/logoToolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
Fragments don't normally intercept back/up presses. That is something that's normally done at the activity level. The reasoning behind that is because you can have multiple fragments on screen at the same time... so which one handles the back press first?
To handle it in your activity, consider keeping track of your before and after state. Let's use the fragment count as an example state:
#Override
public void onBackPressed() {
// for every back press, if there is a fragment to remove, then remove it first
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
return;
}
super.onBackPressed();
}
You also need to make sure you add your original fragment transaction to the backstack:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
newsFrag1 newsFragment1 = new newsFrag1();
ft.replace(R.id.fragment_container, newsFragment1);
ft.addToBackStack();
ft.commit();
Edit: I think from your xml what you're asking for is UP navigation, not BACK navigation. If that is the case, then you still need to leverage the backstack but all the work needs to be done by the parent activity (because the activity owns the toolbar)
getSupportFragmentManager()
.addOnBackStackChangedListener(new OnBackStackChangedListener(){
#Override
public void onBackStackChanged() {
updateToolbarUp();
}
});
public void updateToolbarUp(){
boolean showUp = getSupportFragmentManager().getBackStackEntryCount() > 0;
getSupportActionBar().setDisplayHomeAsUpEnabled(showUp);
}
Then override the up press to simply pop the backstack:
#Override
public boolean onSupportNavigateUp() {
getSupportFragmentManager().popBackStack();
return true;
}

Why layout does not become invisible?

So my layout is still visible, maybe someone sees mistake? I want to dispear it when infoButton(imagebutton) is clicked.
FrameLayout infolayout;
infolayout = (FrameLayout) findViewById(R.id.infoLayout);
public void infoPressed(View v){//info button is pressed by user
//infoLayout.setVisibility(View.GONE);
infolayout.setVisibility(View.INVISIBLE);
}
<FrameLayout
android:layout_width="193dp"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/serviceLayout"
android:id="#+id/infoLayout">
I wacthed: How to change visibility of layout programaticly
EDITED:
wrong code part, still not working for me
*Try this**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.demo.MainActivity" >
<FrameLayout
android:id="#+id/serviceLayout"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#000000" />
<Button
android:id="#+id/btnHide"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="infoPressed"
android:text="Hide" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity
{
FrameLayout infolayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infolayout = (FrameLayout) findViewById(R.id.serviceLayout);
}
public void infoPressed(View v){ //info button is pressed by user
//infoLayout.setVisibility(View.GONE);
infolayout.setVisibility(View.INVISIBLE);
}
}
if your ID declaration is correct I guess you have to change the line
infolayout.setVisibility(View.INVISIBLE);
to
infolayout.setVisibility(FrameLayout.INVISIBLE);

Categories