ViewStub is Not Inflating and Layout Remains Blank - Android - java

I am working through the sample code that is generated when you start a Navigation Drawer Activity in Android Studio. What I am trying to do is change an included view programatically and my research has shown that ViewStub is the best way to do this. However I cannot get it working. For the main layout in question there are 3 files involved:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_main.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="com.MY_APP.android.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
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>
<ViewStub
android:id="#+id/main_content"
android:inflatedId="#id/main_content"
android:layout="#layout/content_main"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
<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="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main"
tools:context="com.MY_APP.android.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/content_textview"
android:text="//TODO Main Feed"/>
</RelativeLayout>
Following is my MainActivity.java. Nothing seems to be happening and content_main never seems to show up. Could it be a visibility issue?
package com.myapp.android;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.ViewStub;
import android.widget.Toast;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity
extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NetworkHelpers NetworkHelper = new NetworkHelpers();
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if user is connected
if(!NetworkHelper.checkConnectivity(this)){
NetworkHelper.showNotConnectedAlert(this);
}
//Check for Google Play Services
checkGooglePlayServicesAvailable();
//Get User Info From Database
sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE);
String login_token = sharedpreferences.getString("login_token", "");
String first_name = sharedpreferences.getString("first_name", "");
String last_name = sharedpreferences.getString("last_name", "");
String email = sharedpreferences.getString("email", "");
if (login_token.isEmpty()){
//Start LoginActivity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}else{
//Update user info
ArrayList<String> params = new ArrayList<String>();
params.add(login_token);
new getUserInfo().execute(params);
}
//Create View
super.onCreate(savedInstanceState);
setContentView(com.myapp.android.R.layout.activity_main);
//Set Toolbar and Navigation Drawer
Toolbar toolbar = (Toolbar) findViewById(com.myapp.android.R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, com.myapp.android.R.string.navigation_drawer_open, com.myapp.android.R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(com.myapp.android.R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ViewStub stub = (ViewStub) findViewById(R.id.main_content);
stub.setLayoutResource(R.layout.content_main);
stub.inflate();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_home) {
// Start Home Screen
} else if (id == R.id.nav_videos) {
// Start Videos Screen
} else if (id == R.id.nav_photos) {
// Start Photos Screen
} else if (id == R.id.nav_galleries) {
// Start Galleries Screen
} else if (id == R.id.nav_map) {
// Start Map Screen
} else if (id == com.myapp.android.R.id.nav_share) {
//Open share app dialog
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "My App");
intent.putExtra(Intent.EXTRA_TEXT, "Check out My App: http://myapp.com/app");
Intent chooser = Intent.createChooser(intent, "Tell a friend about My App");
startActivity(chooser);
} else if (id == com.myapp.android.R.id.nav_logout){
logout();
}
DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//AsyncTask to get user info from api
class getUserInfo extends AsyncTask<ArrayList<String>, Void, String> {
#Override
protected String doInBackground(ArrayList<String>... params) {
String token = params[0].get(0);
String response = HttpRequest.post("http://api.myapp.com/users/get-info/").send("api_key=API_KEY&token="+token).body();
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
try {
// Do JSON Stuff
JSONObject jsonobject = new JSONObject(result);
String status = jsonobject.get("status").toString();
String message = jsonobject.get("message").toString();
JSONObject userinfo = jsonobject.getJSONObject("user_info");
//Set up user variables
String first_name = userinfo.get("first_name").toString();
String last_name = userinfo.get("last_name").toString();
String email = userinfo.get("email").toString();
String display_name = userinfo.get("display_name").toString();
String about = userinfo.get("about").toString();
String newsletter = userinfo.get("newsletter").toString();
if (status.equals("success")){
updateSharedPreferences(first_name, last_name, email, display_name, about, newsletter);
}else if (status.equals("error")){
logout();
} else{
logout();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"An unknown error occurred.", Toast.LENGTH_SHORT).show();
logout();
}
}
}
private boolean checkGooglePlayServicesAvailable() {
final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (status == ConnectionResult.SUCCESS) {
return true;
}
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(status, this, 1);
if (errorDialog != null)
{
errorDialog.show();
}
}
return false;
}
private void updateSharedPreferences(String first_name, String last_name, String email, String display_name, String about, String newsletter){
//Put user info into sharedpreferences
SharedPreferences sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("first_name", first_name);
editor.putString("last_name", last_name);
editor.putString("email", email);
editor.putString("display_name", display_name);
editor.putString("about", about);
editor.putString("newsletter", newsletter);
editor.commit();
}
private void logout(){
//Logout of Facebook
FacebookSdk.sdkInitialize(this);
LoginManager.getInstance().logOut();
//Unset shared preferences login token
SharedPreferences sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("login_token", "");
editor.putString("facebook_token", "");
editor.putString("google_token", "");
editor.commit();
//Open login screen
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
finish();
startActivity(intent);
}
}

I have come across the same issue. It seems that when you are dynamically inflating the StubView, the behaviour is different than when you just use the <include> tag to include another xml layout. In this case, after being inflated the content that replaces the StubView is not positioned below the AppBar layout, but is positioned exactly behind it.
One way to solve this issue, is to move the RelativeLayout so that it wraps the StubView. So, the below changes are needed:
app_bar_main.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="com.MY_APP.android.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
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>
<!-- Changed Content -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main"
tools:context="com.MY_APP.android.MainActivity">
<ViewStub
android:id="#+id/main_content"
android:inflatedId="#id/main_content"
android:layout="#layout/content_main"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</RelativeLayout>
<!-- Changed Content -->
<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="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/content_textview"
android:text="//TODO Main Feed"/>

Related

NavigationDrawer blocks/stops other buttons on the activity

I'm creating an app where once you log in, you can click a button and it leads you to a quiz, however, the Profile activity (activity when you first log in) has a navigation drawer and for some reason, the navigation drawer is blocking the use of the buttons on the Profile that leads to the Quiz activity. Does anyone know how to fix this? If there's anything I can do please let me know. I'm sorry if this is a stupid question this is my first time coding an app.
Profile Java:
package com.example.civis;
import android.content.Intent;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.net.Uri;
import android.widget.Button;
public class Profile extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private Button quizbutton;
private Button enrolbutton1;
//Menu Drawer Set Up
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
quizbutton = (Button) findViewById(R.id.quizbutton);
quizbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openQuiz();
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
// Menu Drawer Navigation
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_profile: // Profile Page Link
Intent i = new Intent(Profile.this, Profile.class);
startActivity(i);
break;
case R.id.nav_current_mps: // Current MP's Link
Intent mpi = new Intent(Profile.this, CurrentMps.class);
startActivity(mpi);
break;
case R.id.nav_local_board: // Local Board Link
Intent locali = new Intent(Profile.this, LocalBoard.class);
startActivity(locali);
break;
case R.id.nav_referendums: // Referendums Link
Intent referendumi = new Intent(Profile.this, Referendums.class);
startActivity(referendumi);
break;
case R.id.nav_elections: // Elections Link
Intent electioni = new Intent(Profile.this, Election.class);
startActivity(electioni);
break;
case R.id.nav_about_us: // About Us Link
Intent aboutusi = new Intent(Profile.this, AboutUs.class);
startActivity(aboutusi);
break;
case R.id.nav_settings: // Settings Link
Intent settingsi = new Intent(Profile.this, Settings.class);
startActivity(settingsi);
break;
case R.id.nav_signout: // Sign Out Link (Links to Sign In Page)
Intent signouti = new Intent(Profile.this, SignIn.class);
startActivity(signouti);
break;
}
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void openQuiz() {
Intent intent = new Intent(this, quiz1.class);
startActivity(intent);
}
}
Profile XML:
<?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/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background"
android:orientation="vertical"
tools:context=".Profile"
tools:openDrawer="start">
<!-- White Card Style Backing -->
<ImageView
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginTop="195dp"
android:background="#drawable/rounded_rectangle_white" />
<!-- Profile Person Image -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_marginTop="90dp"
android:src="#drawable/dp_civis"
tools:ignore="MissingConstraints" />
<!-- Name Area -->
<TextView
android:id="#+id/textView3"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:background="#drawable/edit_text_style"
android:text="Name"
android:textAlignment="center"
android:textSize="24sp" />
<!-- Political Compass Quiz Button -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/quizbutton"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginTop="160dp"
android:background="#drawable/edit_purple_button_style"
android:gravity="center"
android:text="Political Compass Quiz"
android:textColor="#FFF"
tools:ignore="MissingConstraints" />
</LinearLayout>
<!-- Enrol to Vote Button -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="visible">
<Button
android:id="#+id/enrolbutton1"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginTop="320dp"
android:background="#drawable/edit_purple_button_style"
android:gravity="center"
android:text="Enrol to Vote"
android:textColor="#FFF"
tools:ignore="MissingConstraints" />
</LinearLayout>
<!-- Menu Drawer-->
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
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">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#00000000"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
</android.support.v4.widget.DrawerLayout>
Quiz Java:
package com.example.civis;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class quiz1 extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtnAgree;
private Button answerBtnDisagree;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT =5;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
// {Question, Choice 1, Choice 2}
{"All firearms should be registered and it should be tougher to get a licence.", "Agree", "Disagree"},
{"16-year-olds are mature enough to make informed decisions so they should be allowed to vote.", "Agree", "Disagree"},
{"It should be compulsory for everyone in New Zealand to be vaccinated against communicable diseases.", "Agree", "Disagree"},
{"We expect too much of NZ’s Police, and some of their work should be done by communities, mental health experts, and social services.", "Agree", "Disagree"},
{"New Zealand’s borders should remain closed to non-citizens until a COVID-19 vaccine is found, even if that takes years.", "Agree", "Disagree"},
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz1);
countLabel = (TextView)findViewById(R.id.countLabel);
questionLabel = (TextView)findViewById(R.id.questionLabel);
answerBtnAgree = (Button)findViewById(R.id.answerBtnAgree);
answerBtnDisagree = (Button)findViewById(R.id.answerBtnDisagree);
// Create quizArray from quizDara
for (int i = 0; i < quizData.length; i++) {
// Prepare array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); // Question
tmpArray.add(quizData[i][1]); // Agree
tmpArray.add(quizData[i][2]); // Disagree
// Add tmpArray to quizArray.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
// Update quizCountLabel.
countLabel.setText("Q" + quizCount);
// Generate random number between 0 and 1 (quizArray's size -1 )
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
// Pick one quiz set.
ArrayList<String> quiz = quizArray.get(randomNum);
// Set question and right answer.
// Array format: // {Question, Choice 1, Choice 2,}
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
// Remove "Question" from quiz and Shuffle choices
quiz.remove(0);
// Set Choices.
answerBtnAgree.setText(quiz.get(0));
answerBtnDisagree.setText(quiz.get(1));
// Remove this quiz from quizArray.
quizArray.remove(randomNum);
}
public void checkAnswer(View view) {
// Get pushed button.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if(btnText.equals(rightAnswer)) {
alertTitle = "Thank you for responding";
rightAnswerCount++;
} else {
alertTitle = "Thank you for responding";
}
// Create Dialogue
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Your response has been recorded");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (quizCount == QUIZ_COUNT) {
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();;
}
}
});
builder.setCancelable(false);
builder.show();
}
}
Quiz 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"
tools:context=".quiz1"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="#drawable/gradient_background">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/countLabel"
android:text="Q1"
android:textSize="28dp"
android:textColor="#android:color/background_light"
android:layout_marginTop="120dp"/>
<TextView
android:id="#+id/questionLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question"
android:textSize="20dp"
android:layout_gravity="center_horizontal"
android:textColor="#android:color/background_light"
android:layout_marginTop="15dp"/>
<Button
android:id="#+id/answerBtnAgree"
android:layout_width="320dp"
android:layout_height="60dp"
android:layout_marginTop="90dp"
android:text="Agree"
android:background="#drawable/rounded_button"
android:onClick="checkAnswer"/>
<Button
android:id="#+id/answerBtnDisagree"
android:layout_width="320dp"
android:layout_height="60dp"
android:layout_marginTop="40dp"
android:text="Disagree"
android:background="#drawable/rounded_button"
android:onClick="checkAnswer"/>
DrawerLayout should be the parent if you're using NavigationView.
Put the RelativeLayout inside the DrawerLayout.
Your xml should look something like this:
<!-- Menu Drawer-->
<android.support.v4.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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!-- OTHER VIEWS -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
</android.support.v4.widget.DrawerLayout>

Android: Display images in full screen with caption on `onClick` event

I'm a beginner to the android development. I have an android image view that import web image by using Picasso 2.5.2 library. It's working. After click on that imageview, I want to create a full screen Android dialog with that image. I' used following code for it. But after click on the image view, a dialog is displayed without full screen. Finally, I want to zoom in and zoom out that full screen dialog. I want this kind of full screen on imageview onClickListener. Also see how the below image has a title and I also need the image caption (like in Facebook)
Here is my code
Mainactivity.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
ImageView imageView1;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUi();
}
public void initUi(){
imageView1 = (ImageView)findViewById(R.id.image);
Picasso.with(this)
.load(Uri.parse("http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640"))
.into(imageView1);
imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImage();
}
});
}
public void showImage() {
Dialog builder = new Dialog(this, android.R.style.Theme_Light);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
Picasso.with(this)
.load(Uri.parse("http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640"))
.into(imageView);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
builder.show();
}
}
activity_main.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:id="#+id/activity_add_info_other"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:text="Image buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textColor="#android:color/black"
android:textSize="16sp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/image"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
You can use Chrisbane's PhotoView lib for zooming the image.
Open the detail page by sending the path,
public void showImage() {
Intent intent = new Intent(this, ImageDeatilActvity.class);
intent.putExtra("path", "http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640");
startActivity(intent);
}
Complete ImageDeatilActvity.java
public class ImageDeatilActvity extends AppCompatActivity implements View.OnSystemUiVisibilityChangeListener {
private boolean mIsFullScreen;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_deatil_actvity);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_material);
upArrow.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
mIsFullScreen = true;
String path = getIntent().getStringExtra("path");
PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);
photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
#Override
public void onPhotoTap(View view, float x, float y) {
updateView();
}
#Override
public void onOutsidePhotoTap() {
updateView();
}
});
Glide.with(this).load(path).into(photoView);
}
#Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
mIsFullScreen = false;
}
updateView();
}
public void updateView() {
mIsFullScreen = !mIsFullScreen;
if (mIsFullScreen) {
hideSystemUI();
} else {
showSystemUI();
}
}
private void hideSystemUI() {
mToolbar.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2)).start();
}
private void showSystemUI() {
mToolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Detail Activity Layout,
<?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="in.muthu.stackoverflow.ImageDeatilActvity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentTop="true"
android:background="#33000000"
android:fitsSystemWindows="true"
app:contentScrim="#android:color/transparent"
app:popupTheme="#style/AppTheme.AppBarOverlay"/>
<uk.co.senab.photoview.PhotoView
android:id="#+id/photo_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
In My example, I am using Glide not Picaso, because Android
official recommendation is Glide, If you want you can change that.
set image to centre crop and resize it with your screen size like
Picasso.with(MainActivity.this)
.load(Uri.parse("http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640"))
.noFade()
.resize(800, 800)
.centerCrop()
.into(imageView);
Use below xml for layout, i added one more ImageView just use make the visibility visible on click of small image_view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_add_info_other"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:text="Image buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textColor="#android:color/black"
android:textSize="16sp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/image"/>
</LinearLayout>
</ScrollView>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>

How to implement Collapsabletoolbar with ViewPager?

I am trying to implement Collapsabletoolbar, here is my code.
Main.xml
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
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:src="#drawable/hgj_nav"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/tool_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_done" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#009688"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
In java:
public class MainActivityTab extends AppCompatActivity {
// Declaring Your View and Variables
Toolbar toolbar;
CharSequence HGJTitles[]={"Recent News","Category"};
int HGJNumboftabs =2;
private DrawerLayout mDrawerLayout;
private AdView mAdView;
private StartAppAd startAppAd = new StartAppAd(this);
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StartAppAd.init(this, getString(R.string.startapp_dev_id), getString(R.string.startapp_app_id));
setContentView(R.layout.activity_main_tab);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle("");
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivityTab.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
return true;
}
});
StartAppAd.showSlider(this);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
// Prepare the Interstitial Ad
interstitial = new InterstitialAd(MainActivityTab.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
AdRequest adRequest = new AdRequest.Builder().build();
// Load ads into Interstitial Ads
interstitial.loadAd(adRequest);
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
// Call displayInterstitial() function
displayInterstitial();
}
});
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
HitGovtJobAdapter adapter = new HitGovtJobAdapter(getSupportFragmentManager(),HGJTitles,HGJNumboftabs);
ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
MainActivityTab.this.finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
static class HitGovtJobAdapter extends FragmentStatePagerAdapter {
CharSequence HGJTitles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int HGJNumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public HitGovtJobAdapter(FragmentManager fm,CharSequence hgjTitles[], int hgjTabNum) {
super(fm);
this.HGJTitles = hgjTitles;
this.HGJNumbOfTabs = hgjTabNum;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
News_Recent newsRecent = new News_Recent();
return newsRecent;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
News_Category newsCategory = new News_Category();
return newsCategory;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return HGJTitles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return HGJNumbOfTabs;
}
}
public static class HitGovtJobFragment extends Fragment {
private static final String TAB_POSITION = "tab_position";
public HitGovtJobFragment() {
}
public static HitGovtJobFragment newInstance(int tabPosition) {
HitGovtJobFragment fragment = new HitGovtJobFragment();
Bundle args = new Bundle();
args.putInt(TAB_POSITION, tabPosition);
fragment.setArguments(args);
return fragment;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.refresh:
finish();
startActivity(getIntent());
overridePendingTransition(R.anim.open_next, R.anim.close_next);
return true;
case R.id.menu_favorite:
startActivity(new Intent(getApplicationContext(), News_Favorite.class));
return true;
case R.id.menu_about:
Intent about = new Intent(getApplicationContext(), About_Us.class);
startActivity(about);
return true;
case R.id.menu_moreapp:
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(getString(R.string.play_more_apps))));
return true;
case R.id.menu_rateapp:
final String appName = getApplicationContext().getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ appName)));
}
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
protected void onPause() {
mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mAdView.resume();
startAppAd.onResume();
}
#Override
protected void onDestroy() {
mAdView.destroy();
super.onDestroy();
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
But with above code toolbar not collapsed and viewpager scrolls freely. See this image.
And tablayout also not properly placed.
Any idea how can I fix this problem?
Thank you very much in advance.
Use this layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/r`enter code here`es/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"`enter code here`
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<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.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="256dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<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.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:background="#color/colorAccent"
app:tabMode="scrollable"
app:tabContentStart="72dp" />
<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/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="parallax" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="8dp"
android:src="#drawable/ic_menu_camera"
app:layout_anchor="#id/tabLayout"
app:layout_anchorGravity="center|left|start"
app:fabSize="mini"
app:borderWidth="0dp" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
and than your activity
Note ItemFragment can be your fragment having list ItemFragment i am not enclosing this fragment:
package com.example.a61378.navigation;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.example.a61378.navigation.dummy.DummyContent;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,ItemFragment.OnListFragmentInteractionListener {
ViewPager mViewPager;
TabLayout mTabLayout;
String tabPageTitles[] = {"Tab1", "Tab2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
FragmentManager fragment =getSupportFragmentManager();
FragmentHomePagerAdapter fragmentHomePagerAdapter = new FragmentHomePagerAdapter(fragment, tabPageTitles.length);
mViewPager.setAdapter(fragmentHomePagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onListFragmentInteraction(DummyContent.DummyItem item) {
}
class FragmentHomePagerAdapter extends android.support.v4.app.FragmentPagerAdapter {
private int mTabCount;
public FragmentHomePagerAdapter(FragmentManager fm, int tabCount) {
super(fm);
mTabCount = tabCount;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
ItemFragment ViewGroceryfragment = ItemFragment.newInstance(10);
return ViewGroceryfragment;// Fragment # 0 - This will show FirstFragment
}
#Override
public CharSequence getPageTitle(int position) {
return tabPageTitles[position] ;
}
#Override
public int getCount() {
return mTabCount;
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You can use Nested scrollview to achieve this
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabGravity="fill"
app:tabIndicatorColor="#color/dark_orange"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
I have just did it in my project and its working like a boss :P
Edit 1
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
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:src="#drawable/hgj_nav"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/tool_bar"
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>
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="4dp"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_done" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#009688"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
I made a sample project which might help you in what you are looking for it has navigation view collapsing toolbar with viewpager and tabs over viewpager.

Sliding Menu Like Facebook in Material Design theme in Android

I have made a sliding menu like that of facebook by following the tutorial which is available in the following site:
http://www.devexchanges.info/2016/05/creating-your-own-sliding-menu-like.html?m=1
Now in the main layout I have added a long paragraph of text so in order to view everything I used ScrollView. But when I use ScrollView I cannot pull the menu out, I can only open the drawer by clicking on the button. Please help me on how to scroll through the para and also be able to pull the menu drawer.
The MainActivity XML file:
<info.devexchanges.slidingmenu.SlidingLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This holds our menu -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbars="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarmenu"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#102961"
android:orientation="horizontal"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<ListView
android:id="#+id/activity_main_menu_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbarmenu"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<!-- This holds our content-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#drawable/toolbar"
android:orientation="horizontal"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<ImageView
android:id="#+id/menu_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:onClick="toggleMenu"
android:src="#drawable/menu" />
<TextView
android:id="#+id/title"
style="#style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:gravity="center"
android:textColor="#android:color/white" />
</android.support.v7.widget.Toolbar>
<!-- Fragments container layout -->
<FrameLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
the_fiesta Fragment (the home Fragment) XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/white">
<ScrollView
android:layout_width="800dp"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="75dp"
android:src="#drawable/fiesta_title"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_alignParentTop="true"
android:id="#+id/imageView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/the_fiesta"
android:id="#+id/textView"
android:textSize="17sp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_below="#+id/imageView"
android:layout_marginTop="15dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</ScrollView>
Java file of MainActivity:
package info.devexchanges.slidingmenu;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// The SlidingLayout which will hold both the sliding menu and our main content
// Main content will holds our Fragment respectively
SlidingLayout slidingLayout;
// ListView menu
private ListView listMenu;
private String[] listMenuItems;
private Toolbar toolbar;
private TextView title; //page title
private ImageView btMenu; // Menu button
private Fragment currentFragment;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the mainLayout
setContentView(R.layout.activity_main);
slidingLayout = (SlidingLayout) findViewById(R.id.sliding_layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
title = (TextView) findViewById(R.id.title);
setSupportActionBar(toolbar);
// Init menu
listMenuItems = getResources().getStringArray(R.array.menu_items);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listMenu = (ListView) findViewById(R.id.activity_main_menu_listview);
listMenu.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listMenuItems));
listMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onMenuItemClick(parent, view, position, id);
}
});
// handling menu button event
btMenu = (ImageView) findViewById(R.id.menu_icon);
btMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show/hide the menu
toggleMenu(v);
}
});
// Replace fragment main when activity start
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
TheFiesta fragment = new TheFiesta();
ft.add(R.id.activity_main_content_fragment, fragment);
ft.commit();
currentFragment = fragment;
title.setText("The Fiesta");
}
public void toggleMenu(View v) {
slidingLayout.toggleMenu();
}
// Perform action when a menu item is clicked
private void onMenuItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment;
if (position == 0) {
fragment = new TheFiesta();
title.setText("The Fiesta");
} else if (position == 1) {
fragment = new ListViewFragment();
title.setText("Events");
} else if (position == 2) {
fragment = new TextViewFragment();
Bundle args = new Bundle();
args.putString("KEY_STRING", "This is a TextView in the Fragment");
fragment.setArguments(args);
title.setText("Schedule");
} else if (position == 3) {
fragment = new ListViewFragment();
title.setText("Schools");
} else if (position == 4) {
fragment = new ListViewFragment();
title.setText("Updates");
} else if (position == 5) {
fragment = new ListViewFragment();
title.setText("Our Team");
} /*else if (position == 6) {
fragment = new ListViewFragment();
title.setText("About Us");
}*/ else {
fragment = new DummyFragment();
title.setText("About Us");
}
if(!fragment.getClass().equals(currentFragment.getClass())) {
// Replace current fragment by this new one
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
currentFragment = fragment;
}
// Hide menu anyway
slidingLayout.toggleMenu();
}
#Override
public void onBackPressed() {
if (slidingLayout.isMenuShown()) {
slidingLayout.toggleMenu();
} else {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
getSupportActionBar().setTitle("");
}
}
try this instead of Fragments container. add this code below
</android.support.v7.widget.Toolbar> this may work.
<LinearLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:id="#+id/scrollView" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView1" />
</LinearLayout>
</ScrollView>
</LinearLayout>

Cannot get a reference to EditText using 'findViewById()' after 'setContentView()'

In an activity where the user is supposed to enter his credentials, in the 'onCreate(...)' of activity, after setContentView(layout) I am doing this:
nameView = (EditText) findViewById(R.id.profileNameTextBox);
Where nameView is an EditText. When I try to get the text from this variable on a button click, my application crashes. The reason behind it is that nameView holds a null object reference. I can't really understand the reason behind because the function 'findViewById(...)' returns a valid reference to every other View object like Button, Spinner, Image but returns null when called for EditText. I have rechecked the ids multiple times and cross checked almost every little dependency, googled a lot but can't really find the solution, or the cause of the problem.
Bottom line is that the function findViewById is returning null to an object which clearly exists in the layout file with the same id used for the search.
Any help regarding this is appreciated.
This is my Activity
package theappman.speedcontacts;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddContact extends AppCompatActivity {
Contact currentContact;
private EditText nameView;
private EditText numberView;
private ImageView imageView;
private Spinner dayView;
private Spinner monthView;
private Spinner yearView;
private Button saveView;
private void loadViews(){
numberView = (EditText) findViewById(R.id.profileNumberTextBox);
imageView = (ImageView) findViewById(R.id.profileImage);
dayView = (Spinner) findViewById(R.id.dateSpinner);
monthView = (Spinner) findViewById(R.id.monthSpinner);
yearView = (Spinner) findViewById(R.id.yearSpinner);
saveView = (Button) findViewById(R.id.saveButton);
nameView = (EditText) findViewById(R.id.profileNameTextBox);
}
private void populateSpinners(){
String[] days = new String[32];
String[] months = new String[13];
String[] years = new String[71];
days[0] = "Day";
months[0] = "Month";
years[0] = "Year";
for (int i=1; i<32; i++){
days[i] = String.valueOf(i+1);
}
for (int i=1,j=69; i<71; i++,j--){
years[i] = String.valueOf(1947+j);
}
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
ArrayAdapter<String> dayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, days);
dayView.setAdapter(dayAdapter);
ArrayAdapter<String> monthAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, months);
monthView.setAdapter(monthAdapter);
ArrayAdapter<String> yearAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, years);
yearView.setAdapter(yearAdapter );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
currentContact = new Contact();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
}
});
loadViews();
populateSpinners();
saveView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (nameView != null) {
String nnn = nameView.getText().toString();
Toast.makeText(AddContact.this, nnn,Toast.LENGTH_LONG).show();
}
Toast.makeText(AddContact.this, "not.",Toast.LENGTH_LONG).show();
}
});
}
public void saveContact(View view){
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
String NAME = t.getText().toString();
//String NUMBER = view.findViewById(R.id.profileNumber).toString();
Toast.makeText(AddContact.this, "Ok.",Toast.LENGTH_LONG).show();
/*String DATE = day.getSelectedItem().toString() + "-" + month.getSelectedItem().toString() + "-" + year.getSelectedItem().toString();
if (NAME.equals("") || NUMBER.equals("") ){//|| day.getSelectedItem().toString().equals("Day") || month.getSelectedItem().toString().equals("Month") || year.getSelectedItem().toString().equals("Year")){
Toast.makeText(this, "Please fill all fields.",Toast.LENGTH_LONG).show();
return;
}*/
//currentContact.setName(NAME);
//currentContact.setNumber(NUMBER);
//currentContact.setDateOfBirth(DATE );
//save currentContact in database
/*Intent intent = getIntent();
intent.putExtra("key", "Contact Saved");
setResult(RESULT_OK, intent);
finish();*/
}
#Override
public void onBackPressed() {
nameView = (EditText) findViewById(R.id.profileNameTextBox);
Intent intent = getIntent();
intent.putExtra("key", nameView.getText().toString());
setResult(RESULT_OK, intent);
finish();
super.onBackPressed();
}
}
These are my layout files
<?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="theappman.speedcontacts.AddContact">
<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/content_add_contact" />
<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="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
The above file includes the code given below
<?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:orientation="vertical"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="theappman.speedcontacts.AddContact"
tools:showIn="#layout/activity_add_contact">
<ImageView
android:id="#+id/profileImage"
android:src="#drawable/ic_person_black_48dp"
android:layout_width="match_parent"
android:layout_height="200dp" />
<Button
android:id="#+id/selectImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Select Picture"
/>
<EditText
android:name="#+id/profileNameTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Full Name"/>
<EditText
android:name="#+id/profileNumberTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:hint="Enter Phone Number"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:orientation="horizontal"
android:weightSum="3"
>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/dateSpinner"
/>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/monthSpinner"/>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/yearSpinner"/>
</LinearLayout>
<Button
android:id="#+id/saveButton"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:text="Save"
android:layout_gravity="right"
/>
</LinearLayout>
You are initializing the profileNameTextBox at multiple places .
At one place you are using -
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
to initialize profileNameTextBox.
Remove the initialization from saveContact(), onBackPressed() and from anywhere else.You should initialize it only once in loadViews(). That's it. And when you want to access it you can use nameView.
public void saveContact(View view){
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
view is the button clicked. Something tells me that the text box you're looking for is not inside the button.
You created your view variables so you don't have to findViewById all the time. Use them:
EditText t = nameView;

Categories