Why does findViewById() returns "null"? - java

I have an important issue with java
I have this code :
package fr.christian.lbcde;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import fr.christian.lbcde.ui.main.PageViewModel;
import fr.christian.lbcde.ui.main.SectionsPagerAdapter;
public class MainActivity extends AppCompatActivity {
PageViewModel pageViewModel;
View activity_main, tab_create, tab_connect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pageViewModel = new ViewModelProvider(this).get(PageViewModel.class);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
tab_connect = findViewById(R.id.tab_connect);
tab_create = findViewById(R.id.tab_create);
System.out.print("Result of tab_connect : ");
System.out.print(findViewById(R.id.tab_connect));
System.out.print(" ");
System.out.println(tab_connect==null);
System.out.print("Result of tab_create : ");
System.out.print(findViewById(R.id.tab_create));
System.out.print(" ");
System.out.println(tab_create==null);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNew();
}
});
// hideAll();
// tab_connect.setVisibility(View.VISIBLE);
pageViewModel.addTabListener(new PageViewModel.tabChangeListener() {
#Override
public void onChangeTab(View view, int tab) {
switch (tab) {
case 1:
hideAll();
tab_connect.setVisibility(View.VISIBLE);
break;
case 2:
hideAll();
tab_create.setVisibility(View.VISIBLE);
break;
default:
new Toast(getApplicationContext())
.makeText(getApplicationContext(), "Rien a afficher pour cet onglet", Toast.LENGTH_SHORT)
.show();
}
}
});
}
public void addNew() {
new Toast(getApplicationContext())
.makeText(getApplicationContext(), "Cette option n'est pas encore disponible", Toast.LENGTH_SHORT)
.show();
}
public void hideAll() {
View[] views = {
tab_create,
tab_connect
};
for (int i = 0; i < views.length; i++) {
views[i].setVisibility(View.INVISIBLE);
}
;
}
}
and four files for my layouts :
activity main.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.LeBonCoinDeLÉvangile.AppBarOverlay">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="#dimen/appbar_padding"
android:text="#string/app_name"
android:textAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabSelectedTextColor="?attr/colorPrimaryVariant"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:background="?attr/colorPrimary"
app:srcCompat="#android:drawable/ic_menu_info_details" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.PlaceholderFragment">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginEnd="#dimen/activity_horizontal_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<include layout="#layout/login_main"/>
<include layout="#layout/create_main"/>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
create_main.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="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tab_create"
android:orientation="vertical"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginEnd="#dimen/activity_horizontal_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:visibility="invisible">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TAB_CREATE"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BONJOUR LES ÉLËPHANTS"/>
</LinearLayout>
and login_main.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="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tab_connect"
android:orientation="vertical"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginEnd="#dimen/activity_horizontal_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TAB_CONNECT"/>
<TextView
style="#style/h2textStyle"
android:text="#string/titleConnect_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/loginConnect_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
</LinearLayout>
The problem is that at the lines :
System.out.print(findViewById(R.id.tab_connect));
and
System.out.print(findViewById(R.id.tab_create));
I have this result (for the both) :
null
So I can't remove the error "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference" in hideAll(), tab_create.setVisibility(View.VISIBLE), etc... because when I initialize my layouts, they are initialized with a null object (and not my layouts).
I add some lines like
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TAB_CREATE"/>
in my file to see if those tabs are really those I see on my screen and its appear that I really see them (when I cancel the lines with the layouts visibility).
Thanks for your help!

Your tab_connect etc. are included in fragment_main layout and not in activity_main layout that is inflated when you call findViewById() for those ids. The code you posted does not show where you're using fragment_main but what is certain is that it is not in your activity's view hierarchy at the time when you try to look up those views.
Either move the findViewById() calls and whatever you're doing with the views to the fragment, or move the views from the fragment to your main activity.

Related

setDrawerLockMode disable the drawerLayout

Hi guys I search on google about how to disable the swipe that open the drawerLayout i found this 2 codes.
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END);
but these 2 codes disable the opening of drawerLayout from the swipe and from the actionBarDrawerToggle like disabling it at all. Now the question is how can i disable the swipe that opens the drawerLayout without disabling the open by the ActionBarDrawerToggle. This is my application codes.
MainActivity.java
package co.pilot.assist;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
public class MainActivity extends AppCompatActivity {
private DrawerLayout _drawer;
private Toolbar _toolbar;
private boolean isOpen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_drawer = findViewById(R.id._drawer);
_toolbar = findViewById(R.id._toolbar);
drawerSetUp();
}
private void drawerSetUp() {
ActionBarDrawerToggle _toggle = new ActionBarDrawerToggle(MainActivity.this, _drawer, _toolbar,
R.string.app_name, R.string.app_name);
_drawer.addDrawerListener(_toggle);
_toggle.syncState();
_drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
}
main.xml
<androidx.drawerlayout.widget.DrawerLayout 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/_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="start" >
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/_coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<androidx.appcompat.widget.Toolbar
android:id="#+id/_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/arsenic_92" />
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:orientation="vertical" >
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/arsenic_90"
app:menu="#menu/main_bottom_nav_menu" />
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<LinearLayout
android:id="#+id/_nav_view"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#EEEEEE" >
<include layout="#layout/_drawer_main" />
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>

Recycler View inside frame layout not scrolling vertically

I have a recycler view inside fragment "Home" and it is not scrolling vertically. Can someone please help me out !!
My fragment is inside home screen containing a toolbar, drawer navigation and bottom tab navigation . i got another recycler view inside home fragment and that recycler view is not scrolling
This recyclerView is not scrolling >>>
Here is my HomeScreen code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".homeSc"
android:id="#+id/constraintLayout">
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/bottomNavigationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="60dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_nav_menu" />
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawerNavigationDrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/drawerNavigationToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#B3E3E1"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:titleTextColor="#color/black"/>
<FrameLayout
android:id="#+id/drawerNavigationFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:isScrollContainer="true"/>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/drawerNavigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_nav_header"
app:menu="#menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my Home Fragment Code
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frameLayoutHomeSc"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerVFragHomeSc"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
Recycler View Adapter Code
package com.example.knowledgespaceapk;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class adapterRecVHomeFrag extends RecyclerView.Adapter<adapterRecVHomeFrag.myviewholder>{
ArrayList<dataModelRecVFragHome> dataHolder;
public adapterRecVHomeFrag(ArrayList<dataModelRecVFragHome> dataHolder) {
this.dataHolder = dataHolder;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new myviewholder(LayoutInflater.from(parent.getContext()).inflate(R.layout.single_row_design_rec_homef
,parent,false));
}
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.img.setImageResource(dataHolder.get(position).getImage());
holder.title.setText(dataHolder.get(position).getTitle());
holder.desc.setText(dataHolder.get(position).getDescription());
}
#Override
public int getItemCount() {
return dataHolder.size();
}
class myviewholder extends RecyclerView.ViewHolder{
ImageView img;
TextView title,desc;
public myviewholder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.imageVSingleRowDesRecHomeF);
title = itemView.findViewById(R.id.titleTxtVSingleRDesRecHomeF);
desc = itemView.findViewById(R.id.descriptionTxtVSingleRDesRecHomeF);
}
}
}
Recyler View Element layout Code
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="5dp"
android:elevation="4dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageVSingleRowDesRecHomeF"
android:layout_width="match_parent"
android:layout_height="219dp"
android:visibility="visible"
app:srcCompat="#drawable/fest" />
<TextView
android:id="#+id/titleTxtVSingleRDesRecHomeF"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="TextView"
android:textColor="#000000"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/descriptionTxtVSingleRDesRecHomeF"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginLeft="8dp"
android:textColor="#000000"
android:textSize="24sp"
android:textStyle="bold"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
Home Screen Java Code
package com.example.knowledgespaceapk;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import com.example.knowledgespaceapk.databinding.ActivityHomeScBinding;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class homeSc extends AppCompatActivity {
private DrawerLayout drawerLayout;
private BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_sc);
Toolbar toolbar = findViewById(R.id.drawerNavigationToolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawerNavigationDrawerLayout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawerLayout,
toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
replaceFrag(new HomeFragment());
bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnItemSelectedListener(item -> {
switch (item.getItemId()){
case R.id.home : replaceFrag(new HomeFragment()); break;
case R.id.group: replaceFrag(new GroupFragment()); break;
case R.id.notification:replaceFrag(new NotificationFragment()); break;
}
return true;
});
}//End OnCreate
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}else {
super.onBackPressed();
}
}
private void replaceFrag(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,fragment);
fragmentTransaction.commit();
}
}//End Main
Try to set the DrawerLayout as parent view in your HomeScreen XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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/drawerNavigationDrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".homeSc"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/constraintLayout">
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/bottomNavigationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="60dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/drawerNavigationToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#B3E3E1"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:titleTextColor="#color/black"/>
<FrameLayout
android:id="#+id/drawerNavigationFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:isScrollContainer="true"/>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/drawerNavigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_nav_header"
app:menu="#menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>

Do not return back to code from onClickListener onClick method

This part of the code is to add 3 EditText lines while the button secbutt is clicked. While all three EditText lines are on the screen, the button should disappear.
Now I do not understand why after entering onClick method and starting plusTextField method, it just adds EditText lines infinitely. I want it to execute once and to return to the beginning of summonButton method. What should I do?
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
int numberOfLinesLeft = 3;
Button secondaryActivityAddButton;
LinearLayout llForSecondaryButton;
LinearLayout llForSecondaryEditText;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void summonButton(View view){
llForSecondaryButton = findViewById(R.id.secondaryButton);
secondaryActivityAddButton = new Button(this);
secondaryActivityAddButton.setText("" + numberOfLinesLeft);
llForSecondaryButton.addView(secondaryActivityAddButton);
secondaryActivityAddButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
plusTextField();
}
});
}
public void plusTextField() {
llForSecondaryEditText = findViewById(R.id.linearLayout1);
// add edittext
et = new EditText(this);
et.setText("text" + numberOfLinesLeft);
llForSecondaryEditText.addView(et);
numberOfLinesLeft--;
}
}
ActivityMain.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.egrishin.task_a_day.MainActivity">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="#string/main_task_title"
android:gravity="center_horizontal"
/>
<EditText
android:id="#+id/main_task_line_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="What is 1 main thing to be done today?"
android:inputType="textMultiLine"
android:layout_margin="16dp"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout0"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="vertical"
>
<TextView
android:id="#+id/textline2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="#string/secondary_task_title"
android:gravity="center_horizontal"
android:onClick="summonButton"
/>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="16dp"
>
</LinearLayout>
<LinearLayout
android:id="#+id/secondaryButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<TextView android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="#string/other_task_title"
android:gravity="center_horizontal"/>
</LinearLayout>
</LinearLayout>
You miss logic of setting the button invisible when counter riches 0 :
public void onClick(View view) {
plusTextField();
if(numberOfLinesLeft == 0) {
view.setVisibility(View.GONE);
}
}
Here is the result, there is no button after adding 3 Edit Texts:

How to open fragments containing webViews in another activity on button click from fragments of another activity?

I have image-buttons in one of the fragments of an activity and want to open corresponding fragments containing webViews on button clicks in another activity.
I am a beginner so please do give appropriate codes for this.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="com.example.administrator.hiha.MainActivity"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar">
</include>
<fragment
android:id="#+id/upperFragment"
android:layout_width="match_parent"
android:layout_height="200dp"
android:name="com.example.administrator.hiha.Upper_main_Fragment"
android:layout_below="#id/toolbar"
>
</fragment>
<fragment
android:layout_below="#id/upperFragment"
android:id="#+id/lowerFragment"
android:layout_width="match_parent"
android:layout_height="140dp"
android:name="com.example.administrator.hiha.Lower_main_Fragment"
>
</fragment>
<fragment
android:layout_below="#id/lowerFragment"
android:id="#+id/Bottom_Most_Fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.example.administrator.hiha.BottomMostFragment"
tools:layout="#layout/fragment_bottom_most">
</fragment>
<View
android:id="#+id/hLastRow"
android:layout_centerHorizontal="true"
android:layout_below="#id/Bottom_Most_Fragment"
android:layout_width="300dp"
android:layout_height="2dp"
android:background="#EEEEEE"
/>
<TextView
android:layout_alignParentBottom="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/hLastRow"
android:layout_centerHorizontal="true"
android:text="Designed \u0026 Developed by me © 2016."/>
</RelativeLayout>
</ScrollView>
MainActivity.java
package com.example.administrator.hiha;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
//Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//toolbar=(Toolbar)findViewById(R.id.toolbar);
}
}
fragment_lower_main.xml
<FrameLayout 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.administrator.hiha.Lower_main_Fragment">
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="100dp"
android:layout_height="80dp"
android:src="#drawable/about_board"
android:id="#+id/about_img_btn"
android:onClick="onAboutBoardClick"
/>
<TextView
android:id="#+id/text_about_img_btn"
android:text="About Board"
android:layout_below="#id/about_img_btn"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="center"
/>
<ImageButton
android:layout_width="100dp"
android:layout_height="80dp"
android:src="#drawable/sarasvati"
android:id="#+id/sarasvati_img_btn"
android:layout_toRightOf="#id/about_img_btn"
android:onClick="onSarasvatiClick"
/>
<TextView
android:layout_toRightOf="#id/text_about_img_btn"
android:id="#+id/text_sarasvati_img_btn"
android:text="Sarasvati"
android:layout_below="#id/sarasvati_img_btn"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="center"
/>
<ImageButton
android:layout_toRightOf="#id/sarasvati_img_btn"
android:layout_width="100dp"
android:layout_height="80dp"
android:src="#drawable/scientific_evidences"
android:id="#+id/scientific_evidences_img_btn"
android:onClick="onScientificEvidencesClick"
/>
<TextView
android:layout_toRightOf="#id/text_sarasvati_img_btn"
android:id="#+id/text_scientific_evidences_img_btn"
android:text="Scientific EVidences"
android:layout_below="#id/scientific_evidences_img_btn"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="center"
/>
<ImageButton
android:layout_toRightOf="#id/digital_library_img_btn"
android:layout_width="100dp"
android:layout_height="80dp"
android:src="#drawable/affltd_organization"
android:id="#+id/affltd_oragnization_img_btn"
android:onClick="onAffltdOrganizationClick"
/>
<TextView
android:layout_toRightOf="#id/text_digital_library_img_btn"
android:id="#+id/text_affltd_oragnization_img_btn"
android:text="Affiliated Organizations"
android:layout_below="#id/affltd_oragnization_img_btn"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="center"
/>
<ImageButton
android:layout_toRightOf="#id/affltd_oragnization_img_btn"
android:layout_width="100dp"
android:layout_height="80dp"
android:src="#drawable/tender"
android:id="#+id/tender_img_btn"
android:onClick="onTenderClick"
/>
<TextView
android:layout_toRightOf="#id/text_affltd_oragnization_img_btn"
android:id="#+id/text_tender_img_btn"
android:text="Tenders"
android:layout_below="#id/tender_img_btn"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="center"
/>
</RelativeLayout>
</LinearLayout>
</HorizontalScrollView>
</FrameLayout>
Lower_Main_Fragment.java
package com.example.administrator.hiha;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class Lower_main_Fragment extends Fragment {
ImageButton about_img_btn;
ImageButton sarasvati_img_btn;
ImageButton scientific_evidences_img_btn;
ImageButton digital_library_img_btn;
ImageButton affltd_oragnization_img_btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView=inflater.inflate(R.layout.fragment_lower_main_,container,false);
//cast image buttons
about_img_btn=(ImageButton)getView().findViewById(R.id.about_img_btn);
sarasvati_img_btn=(ImageButton)getView().findViewById(R.id.sarasvati_img_btn);
scientific_evidences_img_btn=(ImageButton)getView().findViewById(R.id.scientific_evidences_img_btn);
digital_library_img_btn=(ImageButton)getView().findViewById(R.id.digital_library_img_btn);
affltd_oragnization_img_btn=(ImageButton)getView().findViewById(R.id.affltd_oragnization_img_btn);
return rootView;
}
//onclick methods of image buttons
public void onAboutBoardClick(View view){
}
}
These are the files in which i want that if i click on about_img_btn then it should open a fragment containing a webView in another activity. The same should be repeated for all the buttons.
Please define the further code that i have to use and mention the files where i have to use it. Thanks!
try this:
in your fragment_lower_main xml:
Give an id to the Framelayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.hiha.Lower_main_Fragment">
<FrameLayout
android:id="+#id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<--Rest of the code -->
/>
</LinearLayout>
Now in code open new Fragment during button click using:
about_img_btn=(ImageButton)rootView.findViewById(R.id.about_img_btn);
about_img_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AboutUS fragment = new AboutUS();
Replace_fragment(fragment); //pass the fragment u want to replace
}
});
public void ReplaceFragment(Fragment r_fragment) {
FragmentManager fragmentManager = getActivity.getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_container, r_fragment).commit();
}

button BACK to a collapsingToolbar - Android

It happens that from my main activity I call an activity in that activity that I call tale with collapsingToolbar, well everything works fine only that I can not give BACK because the collapsinToolbar does not generate a button back.
Java code of the main activity
package com.herprogramacion.alquileres;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.herprogramacion.alquileres.provider.Contrato.Alquileres;
public class ActividadListaAlquileres extends AppCompatActivity implements AdaptadorAlquileres.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {
private RecyclerView listaUI;
private LinearLayoutManager linearLayoutManager;
private AdaptadorAlquileres adaptador;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actividad_lista_alquileres);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Filtro...", Snackbar.LENGTH_LONG)
.setAction("Acción", null).show();
}
});
// Preparar lista
listaUI = (RecyclerView) findViewById(R.id.lista);
listaUI.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
listaUI.setLayoutManager(linearLayoutManager);
adaptador = new AdaptadorAlquileres(this, this);
listaUI.setAdapter(adaptador);
// Iniciar loader
getSupportLoaderManager().restartLoader(1, null, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_actividad_lista_alquileres, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(AdaptadorAlquileres.ViewHolder holder, String idAlquiler) {
// Snackbar.make(findViewById(android.R.id.content), ":id = " + idAlquiler,
// Snackbar.LENGTH_LONG).show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, Alquileres.URI_CONTENIDO, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (adaptador != null) {
adaptador.swapCursor(data);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
Java code of the activity where I generate the collapsingToolbar
package com.herprogramacion.alquileres;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class biografia2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biografia2);
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle("Titulo ");
}
}
Xml code of my main activity
<?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="com.herprogramacion.alquileres.ActividadListaAlquileres">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/contenido_actividad_lista_alquileres" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/icono_filtro" />
</android.support.design.widget.CoordinatorLayout>
Xml code of the activity where I generate the collapsingToolbar
<?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"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="#dimen/detail_backdrop_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginEnd="64dp" >
<ImageView
android:id="#+id/backdrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax"
android:src="#drawable/jack"
android:alpha="0.5"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="170dp"
android:layout_gravity="center">
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/card_margin">
<LinearLayout
style="#style/Widget.CardContent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Info"
android:textAppearance="#style/TextAppearance.AppCompat.Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/lorem_ipsum" />
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/card_margin"
android:layout_marginLeft="#dimen/card_margin"
android:layout_marginRight="#dimen/card_margin">
<LinearLayout
style="#style/Widget.CardContent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Friends"
android:textAppearance="#style/TextAppearance.AppCompat.Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/lorem_ipsum" />
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/card_margin"
android:layout_marginLeft="#dimen/card_margin"
android:layout_marginRight="#dimen/card_margin">
<LinearLayout
style="#style/Widget.CardContent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Related"
android:textAppearance="#style/TextAppearance.AppCompat.Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/lorem_ipsum" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
app:layout_anchor="#id/appbar"
app:layout_anchorGravity="bottom|right|end"
android:src="#drawable/ic_discuss"
android:layout_margin="#dimen/fab_margin"
android:clickable="true"/>
</android.support.design.widget.CoordinatorLayout>
You can add back navigation icon in the xml for Toolbar component using app:navigationIcon attribute.
<android.support.v7.widget.Toolbar
android:id="#+id/materialup.toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:layout_scrollFlags="scroll"
app:navigationIcon="?homeAsUpIndicator" />
You should be able to show the default back button using setDisplayHomeAsUpEnabled:
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Categories