Android Actionbar Tabs and Keyboard Focus - java

Problem
I have a very simple activity with two tabs, and I'm trying to handle keyboard input in a custom view. This works great... until I swap tabs. Once I swap tabs, I can never get the events to capture again. In another application, opening a Dialog and then closing it, however, would allow my key events to go through. Without doing that I've found no way of getting my key events again.
What's the issue here? I can't find any way to get key events once I swap tabs, and am curious what's eating them. This example is pretty short and to the point.
Code
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="#+id/actionbar_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
my_fragment.xml
<?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">
<view
class="com.broken.keyboard.KeyboardTestActivity$MyView"
android:background="#777777"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<requestFocus/>
</view>
</LinearLayout>
KeyboardTestActivity.java
package com.broken.keyboard;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.Context;
public class KeyboardTestActivity extends Activity {
public static class MyView extends View {
public void toggleKeyboard()
{ ((InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, 0); }
public MyView(Context context)
{ super(context); }
public MyView(Context context, AttributeSet attrs)
{ super(context, attrs); }
public MyView(Context context, AttributeSet attrs, int defStyle)
{ super(context, attrs, defStyle); }
// FIRST PLACE I TRY, WHERE I WANT TO GET THE PRESSES
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.i("BDBG", "Key went down in view!");
return super.onKeyDown(keyCode,event);
}
// Toggle keyboard on touch!
#Override
public boolean onTouchEvent(MotionEvent event)
{
if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN)
{
toggleKeyboard();
}
return super.onTouchEvent(event);
}
}
// Extremely simple fragment
public class MyFragment extends Fragment {
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.my_fragment, container, false);
return v;
}
}
// Simple tab listener
public static class MyTabListener implements ActionBar.TabListener
{
private FragmentManager mFragmentManager=null;
private Fragment mFragment=null;
private String mTag=null;
public MyTabListener(FragmentManager fragmentManager, Fragment fragment,String tag)
{
mFragmentManager=fragmentManager;
mFragment=fragment;
mTag=tag;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mFragmentManager.beginTransaction()
.replace(R.id.actionbar_content, mFragment, mTag)
.commit();
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
mFragmentManager.beginTransaction()
.remove(mFragment)
.commit();
}
}
FragmentManager mFragmentManager;
ActionBar mActionBar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the fragment manager
mFragmentManager=getFragmentManager();
mActionBar=getActionBar();
// remove the activity title to make space for tabs
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Add the tabs
mActionBar.addTab(mActionBar.newTab()
.setText("Tab 1")
.setTabListener(new MyTabListener(getFragmentManager(), new MyFragment(),"Frag1")));
mActionBar.addTab(mActionBar.newTab()
.setText("Tab 2")
.setTabListener(new MyTabListener(getFragmentManager(), new MyFragment(),"Frag2")));
}
// OTHER PLACE I TRY, DOESN'T WORK BETTER THAN IN THE VIEW
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.i("BDBG", "Key went down in activity!");
return super.onKeyDown(keyCode,event);
}
}

I've solved my own problem, so I thought I'd share the solution. If there's some wording issue, please correct me in a comment; I'm trying to be as accurate as I can but I'm not entirely an android expert. This answer should also serve as an excellent example of how to handle swapping out ActionBar tabs in general. Whether or not one likes the design of the solution code, it should be useful.
The following link helped me figure out my issue: http://code.google.com/p/android/issues/detail?id=2705
Solution
It turns out, there are two important issues at hand. Firstly, if a View is both android:focusable and android:focusableInTouchMode, then on a honeycomb tablet one might expect that tapping it and similar would focus it. This, however, is not necessarily true. If that View happens to also be android:clickable, then indeed tapping will focus the view. If it is not clickable, it will not be focused by touch.
Furthermore, when swapping out a fragment there's an issue very similar to when first instantiating the view for an activity. Certain changes need to be made only after the View hierarchy is completely prepared.
If you call "requestFocus()" on a view within a fragment before the View hierarchy is completely prepared, the View will indeed think that it is focused; however, if the soft keyboard is up, it will not actually send any events to that view! Even worse, if that View is clickable, tapping it at this point will not fix this keyboard focus issue, as the View thinks that it is indeed focused and there is nothing to do. If one was to focus some other view, and then tap back onto this one, however, as it is both clickable and focusable it would indeed focus and also direct keyboard input to this view.
Given that information, the correct approach to setting the focus upon swapping to a tab is to post a runnable to the View hierarchy for the fragment after it is swapped in, and only then call requestFocus(). Calling requestFocus() after the View hierarchy is fully prepared will both focus the View as well as direct keyboard input to it, as we want. It will not get into that strange focused state where the view is focused but the keyboard input is somehow not directed to it, as will happen if calling requestFocus() prior to the View hierarchy being fully prepared.
Also important, using the "requestFocus" tag within the XML of a fragment's layout will most call requestFocus() too early. There is no reason to ever use that tag in a fragment's layout. Outside of a fragment, maybe.. but not within.
In the code, I've added an EditText to the top of the fragment just for testing tap focus change behaviors, and tapping the custom View will also toggle the soft keyboard. When swapping tabs, the focus should also default to the custom view. I tried to comment the code effectively.
Code
KeyboardTestActivity.java
package com.broken.keyboard;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.Context;
public class KeyboardTestActivity extends Activity {
/**
* This class wraps the addition of tabs to the ActionBar,
* while properly swapping between them. Furthermore, it
* also provides a listener interface by which you can
* react additionally to the tab changes. Lastly, it also
* provides a callback for after a tab has been changed and
* a runnable has been post to the View hierarchy, ensuring
* the fragment transactions have completed. This allows
* proper timing of a call to requestFocus(), and other
* similar methods.
*
* #author nacitar sevaht
*
*/
public static class ActionBarTabManager
{
public static interface TabChangeListener
{
/**
* Invoked when a new tab is selected.
*
* #param tag The tag of this tab's fragment.
*/
public abstract void onTabSelected(String tag);
/**
* Invoked when a new tab is selected, but after
* a Runnable has been executed after being post
* to the view hierarchy, ensuring the fragment
* transaction is complete.
*
* #param tag The tag of this tab's fragment.
*/
public abstract void onTabSelectedPost(String tag);
/**
* Invoked when the currently selected tab is reselected.
*
* #param tag The tag of this tab's fragment.
*/
public abstract void onTabReselected(String tag);
/**
* Invoked when a new tab is selected, prior to {#link onTabSelected}
* notifying that the previously selected tab (if any) that it is no
* longer selected.
*
* #param tag The tag of this tab's fragment.
*/
public abstract void onTabUnselected(String tag);
}
// Variables
Activity mActivity = null;
ActionBar mActionBar = null;
FragmentManager mFragmentManager = null;
TabChangeListener mListener=null;
View mContainer = null;
Runnable mTabSelectedPostRunnable = null;
/**
* The constructor of this class.
*
* #param activity The activity on which we will be placing the actionbar tabs.
* #param containerId The layout id of the container, preferable a {#link FrameLayout}
* that will contain the fragments.
* #param listener A listener with which one can react to tab change events.
*/
public ActionBarTabManager(Activity activity, int containerId, TabChangeListener listener)
{
mActivity = activity;
if (mActivity == null)
throw new RuntimeException("ActionBarTabManager requires a valid activity!");
mActionBar = mActivity.getActionBar();
if (mActionBar == null)
throw new RuntimeException("ActionBarTabManager requires an activity with an ActionBar.");
mContainer = activity.findViewById(containerId);
if (mContainer == null)
throw new RuntimeException("ActionBarTabManager requires a valid container (FrameLayout, preferably).");
mListener = listener;
mFragmentManager = mActivity.getFragmentManager();
// Force tab navigation mode
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
/**
* Simple Runnable to invoke the {#link onTabSelectedPost} method of the listener.
*
* #author nacitar sevaht
*
*/
private class TabSelectedPostRunnable implements Runnable
{
String mTag = null;
public TabSelectedPostRunnable(String tag)
{
mTag=tag;
}
#Override
public void run() {
if (mListener != null) {
mListener.onTabSelectedPost(mTag);
}
}
}
/**
* Internal TabListener. This class serves as a good example
* of how to properly handles swapping the tabs out. It also
* invokes the user's listener after swapping.
*
* #author nacitar sevaht
*
*/
private class TabListener implements ActionBar.TabListener
{
private Fragment mFragment=null;
private String mTag=null;
public TabListener(Fragment fragment, String tag)
{
mFragment=fragment;
mTag=tag;
}
private boolean post(Runnable runnable)
{
return mContainer.post(runnable);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// no fragment swapping logic necessary
if (mListener != null) {
mListener.onTabReselected(mTag);
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mFragmentManager.beginTransaction()
.replace(mContainer.getId(), mFragment, mTag)
.commit();
if (mListener != null) {
mListener.onTabSelected(mTag);
}
// Post a runnable for this tab
post(new TabSelectedPostRunnable(mTag));
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
mFragmentManager.beginTransaction()
.remove(mFragment)
.commit();
if (mListener != null) {
mListener.onTabUnselected(mTag);
}
}
}
/**
* Simple wrapper for adding a text-only tab. More robust
* approaches could be added.
*
* #param title The text to display on the tab.
* #param fragment The fragment to swap in when this tab is selected.
* #param tag The unique tag for this tab.
*/
public void addTab(String title, Fragment fragment, String tag)
{
// The tab listener is crucial here.
mActionBar.addTab(mActionBar.newTab()
.setText(title)
.setTabListener(new TabListener(fragment, tag)));
}
}
/**
* A simple custom view that toggles the on screen keyboard when touched,
* and also prints a log message whenever a key event is received.
*
* #author nacitar sevaht
*
*/
public static class MyView extends View {
public void toggleKeyboard()
{ ((InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, 0); }
public MyView(Context context)
{ super(context); }
public MyView(Context context, AttributeSet attrs)
{ super(context, attrs); }
public MyView(Context context, AttributeSet attrs, int defStyle)
{ super(context, attrs, defStyle); }
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.i("BDBG", "Key (" + keyCode + ") went down in the custom view!");
return true;
}
// Toggle keyboard on touch!
#Override
public boolean onTouchEvent(MotionEvent event)
{
if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN)
{
toggleKeyboard();
}
return super.onTouchEvent(event);
}
}
// Extremely simple fragment
public class MyFragment extends Fragment {
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.my_fragment, container, false);
return v;
}
}
public class MyTabChangeListener implements ActionBarTabManager.TabChangeListener
{
public void onTabReselected(String tag) { }
public void onTabSelected(String tag) { }
public void onTabSelectedPost(String tag)
{
// TODO: NOTE: typically, one would conditionally set the focus based upon the tag.
// but in our sample, both tabs have the same fragment layout.
View view=findViewById(R.id.myview);
if (view == null)
{
throw new RuntimeException("Tab with tag of (\""+tag+"\") should have the view we're looking for, but doesn't!");
}
view.requestFocus();
}
public void onTabUnselected(String tag) { }
}
// Our tab manager
ActionBarTabManager mActionBarTabManager = null;
// Our listener
MyTabChangeListener mListener = new MyTabChangeListener();
// Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// instantiate our tab manager
mActionBarTabManager = new ActionBarTabManager(this,R.id.actionbar_content,mListener);
// remove the activity title to make space for tabs
getActionBar().setDisplayShowTitleEnabled(false);
// Add the tabs
mActionBarTabManager.addTab("Tab 1", new MyFragment(), "Frag1");
mActionBarTabManager.addTab("Tab 2", new MyFragment(), "Frag2");
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="#+id/actionbar_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
my_fragment.xml
<?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">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<!-- note that view is in lower case here -->
<view
class="com.broken.keyboard.KeyboardTestActivity$MyView"
android:id="#+id/myview"
android:background="#777777"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:layout_height="match_parent"
/>
</LinearLayout>

Related

Adding code to Fragment files in Bottomnavigtaionview

I want to know how to code inside a fragment.java file. Firstly, I am a beginner in coding. I have created a Bottomnavigationview with three navigation buttons in the bottomnaviation bar and I have created Fragment activity for each of the navigation buttons. One of the navigation options in the bottom navigation bar is 'more' and I have added a button with the id "btn_Logoff". when I click the button I want it to go the activity_login.xml or LoginActivity.java. I dont know what is the code for that and where to add the code in the default fragment java file so here is what is written on the fragment file by default:
filename is MoreFragment.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MoreFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MoreFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MoreFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public MoreFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MoreFragment.
*/
// TODO: Rename and change types and number of parameters
public static MoreFragment newInstance(String param1, String param2) {
MoreFragment fragment = new MoreFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_more, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
Toast.makeText(context, "Notification Fragment Attached", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Ive been having a lot of trial and errors and still no resolution. Any help appreciated. Thank you.
Can you explain this part?
when I click the button I want it to go the activity_login.xml or LoginActivity.java.
Do you want to execute something in activity after click on button in fragment, am I right?
You can do it for some ways. Easiest is set listener that listening when you clicking on the button.
Create interface:
public interface OnNavigationButtonClickListener {
void onMoreClick();
}
Create listener variable in fragment:
private OnNavigationButtonClickListener navigationListener;
and setter for it:
public void setNavigationListener(OnNavigationButtonClickListener listener) {
this.navigationListener = listener;
}
3.Notify your listeners in fragment on more button click:
onMoreButton.setOnClickListener(new OnClickListener {
navigationListener.onMoreClick();
});
4. Then set listener in your activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragment.setNavigationListener(new OnNavigationButtonClickListener() {
#Override
public void onMoreClick() {
// you clicked 'more' button in fragment
// do what you want
}
});
Assuming thay you already identified btn_Logoff with the findViewById and everything
all you need to do is add a onclickListener that launchs the activity you want, your code for the clicklistener will look similar to this
Button btn_Logoff;
your class{
btn_Logoff = (Button) findViewById(R.id.IdOfYourBtnInTheXmlFile);
btn_Logoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
}

Hiding ‘Bottom Navigation Bar’ whilst keyboard is present - Android

I have a small demo chat UI application. This application has a bottom navigation bar. I need the bottom navigation bar to hide when the keyboard appears.
Here is an example of the chat UI
As you can see when you click in the EditText element, the keyboard appears but the bottom navigation bar stays visible. I have tried methods such as this measurement method, but the UI elements flicker like this.
Is there a proper way to hide the bottom navigation bar when the keyboard is visible?
EDIT:
In the below activity you can see where I set the keyboard listener to adjust the position of UI elements when the keyboard is determined as being visible.
This is my activity code, uses setKeyboardListener method from the above link and set it in onCreateView:
package uk.cal.codename.projectnedry.TeamChatFragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.roughike.bottombar.BottomBar;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import uk.cal.codename.projectnedry.R;
import uk.cal.codename.projectnedry.TeamChatFragment.ListAdapter.TeamChatListAdapter;
import uk.demo.cal.genericmodelviewpresenter.GenericMvp.GenericMvpFragment;
import static android.view.View.GONE;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link TeamChatView.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link TeamChatView#newInstance} factory method to
* create an instance of this fragment.
*/
public class TeamChatView extends GenericMvpFragment implements TeamChatContract.RequiredViewOps {
private OnFragmentInteractionListener mListener;
#BindView(R.id.teamChatList)
RecyclerView mTeamChatRecyclerView;
#BindView(R.id.teamChatSendButton)
ImageButton mTeamChatSendButton;
#BindView(R.id.messageTextInput)
EditText mMessageTextInput;
TeamChatListAdapter mTeamChatListAdapter;
TeamChatListAdapter.ClickListener mTeamChatListClickListener;
private ArrayList<String> mTestMessageList;
public interface OnKeyboardVisibilityListener {
void onVisibilityChanged(boolean visible);
}
public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private boolean wasOpened;
private final int DefaultKeyboardDP = 100;
// From #nathanielwolf answer... Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);
private final Rect r = new Rect();
#Override
public void onGlobalLayout() {
// Convert the dp to pixels.
int estimatedKeyboardHeight = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());
// Conclude whether the keyboard is shown or not.
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
boolean isShown = heightDiff >= estimatedKeyboardHeight;
if (isShown == wasOpened) {
Log.d("Keyboard state", "Ignoring global layout change...");
return;
}
wasOpened = isShown;
listener.onVisibilityChanged(isShown);
}
});
}
public TeamChatView() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment TeamChatView.
*/
public static TeamChatView newInstance() {
TeamChatView fragment = new TeamChatView();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#SuppressLint("MissingSuperCall")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(TeamChatPresenter.class, TeamChatModel.class, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_team_chat_view, container, false);
this.mUnbinder = ButterKnife.bind(this, view);
mTestMessageList = new ArrayList<>();
this.mTeamChatListAdapter = new TeamChatListAdapter(mTestMessageList);
this.mTeamChatRecyclerView.setAdapter(this.mTeamChatListAdapter);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
this.mTeamChatRecyclerView.setLayoutManager(linearLayoutManager);
this.mTeamChatSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!String.valueOf(mMessageTextInput.getText()).equals("")) {
getSpecificImpOfGenericPresenter().sendMessage(String.valueOf(mMessageTextInput.getText()));
mMessageTextInput.setText("");
mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
}
}
});
setKeyboardListener(new OnKeyboardVisibilityListener(){
#Override
public void onVisibilityChanged(boolean visible) {
RelativeLayout contentFrame = (RelativeLayout) getActivity().findViewById(R.id.content_company_navigation);
BottomBar lowerNavigationBar = (BottomBar) getActivity().findViewById(R.id.bottomBar);
if (visible) { // if more than 100 pixels, its probably a keyboard...
lowerNavigationBar.setVisibility(GONE);
contentFrame.setPadding(0, 0, 0, 0);
mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
} else {
contentFrame.setPadding(0, 0, 0, convertDpToPixel(60, getContext()));
mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
lowerNavigationBar.setVisibility(View.VISIBLE);
}
}
});
return view;
}
/**
* This method converts dp unit to equivalent pixels, depending on device density.
*
* #param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
* #param context Context to get resources and device specific display metrics
* #return A float value to represent px equivalent to dp depending on device density
*/
public static int convertDpToPixel(float dp, Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
int px = (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
public void addToTestMessageList(String str){
this.mTestMessageList.add(str);
this.mTeamChatListAdapter.notifyDataSetChanged();
}
#Override
public void onDestroyView() {
super.onDestroyView();
// getView().getViewTreeObserver().removeGlobalOnLayoutListener(test);
}
#Override
public TeamChatPresenter getSpecificImpOfGenericPresenter() {
return (TeamChatPresenter) this.mPresenter;
}
}
This is my XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="uk.cal.codename.projectnedry.TeamChatFragment.TeamChatView">
<android.support.v7.widget.RecyclerView
android:layout_above="#+id/chatViewMessageEntryLayout"
android:id="#+id/teamChatList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:isScrollContainer="false"
android:paddingTop="10dp"
android:scrollbars="vertical" />
<RelativeLayout
android:id="#+id/chatViewMessageEntryLayout"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<View
android:id="#+id/chatViewMessageEntrySeperator"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#e3e3e8" />
<EditText
android:id="#+id/messageTextInput"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_below="#+id/chatViewMessageEntrySeperator"
android:layout_toLeftOf="#+id/teamChatSendButton"
android:background="#android:color/transparent"
android:hint="Enter message"
android:inputType="textCapSentences|textMultiLine"
android:maxLength="1000"
android:maxLines="4"
android:paddingLeft="10dp" />
<ImageButton
android:id="#+id/teamChatSendButton"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_gravity="center"
android:background="#00B9EF"
android:src="#drawable/ic_send_white_24dp" />
</RelativeLayout>
</RelativeLayout>
The easiest implementation, Add AndroidManifest.xml in
<activity android:windowSoftInputMode="adjustPan"/>
hopefully this helps someone out. Enjoy !
you just add this code in your manifest like this way..
<activity android:name=".MainActivity"
android:windowSoftInputMode="adjustPan">
this works for me.. happy coding
I ended up using the height measuring method that seems to be the standard way of soft keyboard detection which is described in this answer. However, I used this library's implementation of it, as it is still the same ViewTreeObserver.OnGlobalLayoutListener method, implemented well, and allowed me to abstract the code out of my applications main codebase.
When this keyboard visibility listener is triggered, I then hide/show the bottom navigation bar (which I have explained here).
Add this line in onResume() of your Activity or Fragment.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
It is worked for me. Just try it once.
Just add the attribute below to every activity in your AndroidManifest.xml file.
<activity
android:name=".MainActivity"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
Actively listen for the Keyboard(IME) open/close events and show/hide bottom navigation accordingly.
We can make use of the WindowInsetsCompat API which makes this job effortless.
Step 1: Make sure you have migrated to AndroidX
Step 2: In your Fragment inside onCreateView add the listener for Keyboard(IME) events
ViewCompat.setOnApplyWindowInsetsListener(window.decorView.rootView) { _, insets ->
//This lambda block will be called, every time keyboard is opened or closed
val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
if(imeVisible){
//Now show-hide bottom navigation accordingly
}
insets
}
This is all you need🎉
For more info on window insets, you can check out this in-depth article
NOTE:Earlier detecting Keyboard open/close events was not an easy task. Android Devs resorted to all types of hacks to accomplish this. But after decades of requests, prayers and rants Google finally came up with WindowInsets API. Thank you, Google🙏🏻
private boolean keyboardListenersAttached = false;
private ViewGroup rootLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_settings, container, false);
rootLayout = (ViewGroup) view.findViewById(R.id.settings_layout);
attachKeyboardListeners();
return view;
}
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new
ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int heightDiff = rootLayout.getRootView().getHeight() -
rootLayout.getHeight();
if (getActivity() != null) {
int contentViewTop =
getActivity().getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
LocalBroadcastManager broadcastManager =
LocalBroadcastManager.getInstance(getContext());
Rect r = new Rect();
rootLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = rootLayout.getRootView().getHeight();
// r.bottom is the position above soft keypad or device button.
// if keypad is shown, the r.bottom is smaller than that before.
int keypadHeight = screenHeight - r.bottom;
if (keypadHeight > screenHeight * 0.15) {
onHideKeyboard();
Intent intent = new Intent("KeyboardWillHide");
broadcastManager.sendBroadcast(intent);
} else {
int keyboardHeight = heightDiff - contentViewTop;
onShowKeyboard(keyboardHeight);
Intent intent = new Intent("KeyboardWillShow");
intent.putExtra("KeyboardHeight", keyboardHeight);
broadcastManager.sendBroadcast(intent);
}
}else {
}
}
};
protected void onShowKeyboard(int keyboardHeight) {
System.out.println("keyboard is shown");
dashboardActivity.bottomNavigationView.setVisibility(View.VISIBLE);
dashboardActivity.fab.setVisibility(View.VISIBLE);
}
protected void onHideKeyboard() {
System.out.println("keyboard is hide");
dashboardActivity.bottomNavigationView.setVisibility(View.INVISIBLE);
dashboardActivity.fab.setVisibility(View.INVISIBLE);
}
protected void attachKeyboardListeners() {
if (keyboardListenersAttached) {
return;
}
rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);
keyboardListenersAttached = true;
}
in Manifest.xml file add
<activity
android:name=".Activity.DashboardActivity"
android:windowSoftInputMode="adjustResize"
/>
For API 21+:
Firstly, set "android:windowSoftInputMode" for the activity to "adjustResize" in AndroidManifest.xml
Secondly, in your acticity's onCreate method register the following listener:
window.decorView.setOnApplyWindowInsetsListener { view, insets ->
val insetsCompat = toWindowInsetsCompat(insets, view)
val isImeVisible = insetsCompat.isVisible(WindowInsetsCompat.Type.ime())
// below line, do the necessary stuff:
dataBinding.bottomNavigation.visibility = if (isImeVisible) View.GONE else View.VISIBLE
view.onApplyWindowInsets(insets)
}
Add the attribute : android:windowSoftInputMode="adjustResize"" in your manifest inside activity tag:
<activity
android:name=".YourActivity"
android:windowSoftInputMode="adjustResize"/>
NB: I suggest, You should use NestedScrollView as the parent layout.
Hope this helps.
In my case, I am using DrawerLayout as a parent view with some layout content and A Navigation Bottom Bar.
In Manifest file add "android:windowSoftInputMode="adjustPan" this TAG with Activity and this working fine.
<activity android:name=".Activities.OrderSceenWithOrder"
android:windowSoftInputMode="adjustPan"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
That answer might be helpful for people still looking for solution.
Bottom Navigation bar moves up with keyboard
Add this onResume() in your fragment
#Override
public void onResume() {
Objects.requireNonNull(getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
super.onResume();
}
Hope this helps someone!
That solution works for me and it also doesn't show overlapped bottom navbar
just add this line to your activity:
android:windowSoftInputMode="adjustResize|adjustPan"

How to link two xml pages in Android app when a button is clicked?

I am making a simple app in which on home page, a button is placed. When the button is clicked, it must display a new page (xml in layout). How to do that ..
My app contains in src directory, There are two java files.
1. Activity2
2. Main_activity
and two xml files in layout:
1. fragment_main.xml
2. Activity.xml
I want that when i click "Technical button", it should display Activity.xml page from layout..
My codes:
Main_Activity.java
package com.example.vit;
import java.util.Locale;
import android.util.Log;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void onClick(View v)
{
Intent intent = new Intent (v.getContext(),Activity.class);
startActivityForResult (intent,0);
}
}
2.Activity2.java
package com.example.vit;
import android.app.Activity;
public class Activity2 extends Activity
public void onCreate(Bundle, savedInstanceState)
{
{
super.onCreate(savedInstanceState);
setContentView(R.layout.Activity);
}
}
3. fragment_main.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.vit.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="31dp"
android:onClick="doSomething"
android:text="Technical" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Non Technical" />
</LinearLayout>
Activity.xml
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your request is being processed"
android:textAppearance="?android:attr/textAppearanceLarge" />
Intent intent = new Intent(this, ActivityTwo.class);
this.startActivity ( intent );
Note : #Don already provided a correct answer, but (sorry) lack of information. Accept his answer, i only help to add some informations (which is quite long if i put in comment)
In Android, a page/screen in your apps refer to the subclass of Activity. An Activity always have a xml layout.
So, if you want to change from one layout (or screen/page) to others, you should change the Activity, with the help of Intent class. This will automatically change the layout (as your question refer) because an Activity has a layout.
No offense, but i suggest you to search some videos/books/tutorials. I suggest Commonsware's book which is free (the old version, but still the best book in my opinion) :
http://commonsware.com/Android/4-2-free
all is going right but u have to include the following code
Intent intent = new Intent(this, ActivityTwo.class);
this.startActivity ( intent );

How can I add a large profile picture to my navigation drawer?

So, a couple of days ago I started working on my very first app. It's an app with a navigation drawer where users can set some website shortcuts to be displayed in the navigation drawer. If a user clicks on a website it opens in a webview. Really nothing fancy, but it's a concept I came up with to train my Android knowledge.
I finished the basics of this app this morning with some help, but now I want to add a large profile picture to the navigation drawer. (You can see it here on the left: http://www.droid-life.com/wp-content/uploads/2013/12/new-foursquare.jpg)
I understand that I should add an <ImageView> to the navigation drawer, but every time I try that the log keeps saying I have junk in my XML...
Below you can find the code I already wrote. I hope you guys can help me...
Main.java
package test.webviewapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Main
extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks
{
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
// we need a class level references to some objects to be able to modify the
// target address outside of onCreate()
private WebView myWebView;
private ActionBar actionBar;
private ProgressDialog progressDialog;
// keep the pair of String arrays of site names and addresses
private String[] siteNames;
private String[] siteAddresses;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// grab the needed website arrays
siteNames = getResources().getStringArray(R.array.site_names);
siteAddresses = getResources().getStringArray(R.array.site_addresses);
// set up WebView. initial page load comes from NavDrawerFragment attach
myWebView = (WebView) findViewById(R.id.main_webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// when a page has finished loading dismiss any progress dialog
if (progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
String javascript="javascript:"+
"document.getElementById('menu-toggle').css('display','none');";
myWebView.evaluateJavascript(javascript, null);
}
});
// Set up the drawer.
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int siteIndex)
{
// user selected page load
Log.d(TAG, "(onNavSelect) received index: " + siteIndex);
loadWebPage(siteIndex);
}
public void onSectionAttached(int siteIndex)
{
// initial page load. not user selected.
loadWebPage(siteIndex);
}
public void restoreActionBar()
{
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
private void loadWebPage(int siteIndex)
{
// lets show a progress indicator instead of a blank screen
if (progressDialog == null)
{
initProgressDialog();
}
progressDialog.show();
// load the page
Log.d(TAG, "(loadWebPage) Loading page: " + siteNames[siteIndex] + "("
+ siteAddresses[siteIndex] + ")");
mTitle = siteNames[siteIndex];
if (actionBar == null)
{
restoreActionBar();
}
else
{
actionBar.setTitle(mTitle);
}
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl(siteAddresses[siteIndex]);
myWebView.loadUrl(siteAddresses[siteIndex]);
// progressDialog gets dismissed above in WebViewclient declaration
}
private void initProgressDialog()
{
progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setMessage(getString(R.string.page_load_progress_message));
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
if (!mNavigationDrawerFragment.isDrawerOpen())
{
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.global, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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.
if (actionBar == null)
{
restoreActionBar();
}
else
{
}
int id = item.getItemId();
if (id == R.id.action_settings)
{
myWebView.loadUrl(settingsview);
myWebView.loadUrl(settingsview);
actionBar.setTitle("Settings");
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment
extends Fragment
{
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SELECTED_SITE_INDEX = "selected_site_index";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int siteIndex)
{
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SELECTED_SITE_INDEX, siteIndex);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment()
{}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
// Here is where you can define the default page you want loaded
// or if you want to save/restore the last page viewed etc.
((Main) activity)
.onSectionAttached(getArguments().getInt(ARG_SELECTED_SITE_INDEX));
}
}
}
NavigationDrawerFragment.java
package test.webviewapp;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Fragment used for managing interactions for and presentation of a
* navigation drawer. See the <a href=
* "https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"
* > design guidelines</a> for a complete explanation of the behaviors
* implemented here.
*/
public class NavigationDrawerFragment
extends Fragment
implements AdapterView.OnItemClickListener
{
private String[] siteNames;
private static final String TAG = "NavDrawerFrag";
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until
* the user manually expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment()
{}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null)
{
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
// too early to select an item
//selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
selectItem(mCurrentSelectedPosition);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
siteNames = getActivity().getResources().getStringArray(R.array.site_names);
Log.d(TAG, "number of sites loaded: " + siteNames.length);
mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer,
container,
false);
// neater to implement OnItemClickListener and define onClick() later
mDrawerListView.setOnItemClickListener(this);
String[] siteNames = getActivity().getResources().getStringArray(R.array.site_names);
mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar().getThemedContext(),
android.R.layout.simple_list_item_1, android.R.id.text1, siteNames));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen()
{
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation
* drawer interactions.
*
* #param fragmentId
* The android:id of this fragment in its activity's layout.
* #param drawerLayout
* The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout)
{
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout,
R.drawable.ic_drawer, R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
{
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
if (!isAdded())
{
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
if (!isAdded())
{
return;
}
if (!mUserLearnedDrawer)
{
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState)
{
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable()
{
#Override
public void run()
{
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int siteIndex)
{
mCurrentSelectedPosition = siteIndex;
if (mDrawerListView != null)
{
Log.d(TAG, "(select) list ok");
mDrawerListView.setItemChecked(siteIndex, true);
}
if (mDrawerLayout != null)
{
Log.d(TAG, "(select) drawer ok");
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null)
{
Log.d(TAG, "(select) callback...");
mCallbacks.onNavigationDrawerItemSelected(siteIndex);
}
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
mCallbacks = (NavigationDrawerCallbacks) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach()
{
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen())
{
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (mDrawerToggle.onOptionsItemSelected(item))
{
//fragment = new PlanetFragment();
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to
* show the global app 'context', rather than just what's in the current
* screen.
*/
private void showGlobalContextActionBar()
{
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar()
{
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.i(TAG, "(Click) index: " + position);
Log.i(TAG, "(Click) site: " + siteNames[position]);
selectItem(position);
}
/**
* Callbacks interface that all activities using this fragment must
* implement.
*/
public static interface NavigationDrawerCallbacks
{
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
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:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<fragment
android:id="#+id/navigation_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="test.webdrawerapp.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main$PlaceholderFragment">
</RelativeLayout>
fragment_navigation_drawer.xml
<ListView 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:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#000"
tools:context=".NavigationDrawerFragment" />
From working with you on this app before I was able to make some tweaks for you.
What had to be done was to add new Views to fragment_navigation_drawer.xml and change the NavigationDrawerFragment to match up and include the changes.
Layout
<?xml version="1.0" encoding="utf-8"?>
<!-- the root view is now a LinearLayout, all other Views are children of this -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#cccc"
android:orientation="vertical">
<!-- a separate section to go above the list -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:orientation="horizontal">
<!-- your image, you can set it later (see NavDrawerFrag) -->
<ImageView
android:id="#+id/nav_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:src="#android:drawable/ic_menu_myplaces"/>
<!-- a bit of test or a title to go with it -->
<TextView
android:id="#+id/nav_text"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Default text"/>
</LinearLayout>
<!-- some divider thing -->
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:padding="20dp"
android:background="#000000"/>
<!-- your ListView is now a child View -->
<ListView
android:id="#+id/nav_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"/>
</LinearLayout>
Fragment
// new class level members
private ImageView mDrawerImage;
private TextView mDrawerText;
// change the View inflation and extract the new child views
// also modifying the ListView to now be a child instead of the root View
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
// need site names for list
siteNames = getActivity().getResources().getStringArray(R.array.site_names);
Log.d(TAG, "number of sites loaded: " + siteNames.length);
// inflate the parent view (the entire layout)
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
// now grab the separate child views from inside it
mDrawerListView = (ListView) view.findViewById(R.id.nav_listView);
mDrawerImage = (ImageView) view.findViewById(R.id.nav_image);
mDrawerText = (TextView) view.findViewById(R.id.nav_text);
// configure the Views
mDrawerText.setText("Give it a name/title");
//mDrawerImage.setImageURI(...); // set your ImageView however you want, I just gave it one in XML
mDrawerListView.setOnItemClickListener(this);
mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar().getThemedContext(),
android.R.layout.simple_list_item_1, android.R.id.text1, siteNames));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
// and return the inflated view up the stack
return view;
}

webView cannot be resolved & cannot make a static reference to the non-static method findViewById(int) from the type Activity

MainActivity.java code
package com.themeister.feed.it;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
View webView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
WebView wv = (WebView)rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.stackoverflow.com");
return rootView;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1"
android:orientation="vertical">
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.9"/>
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.1"
style="?android:attr/progressBarStyleHorizontal"/>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
</LinearLayout>
What I'm trying to do is for testing purpose load up http://www.stackoverflow.com in my app and navigate on the website. The following code returns two errors:
"Cannot make a static reference to the non-static method findViewById(int) from the type Activity MainActivity.java /Feed.it/src/com/themeister/feed/it line 168 Java Problem"
and
"webView cannot be resolved MainActivity.java /Feed.it/src/com/themeister/feed/it line 169 Java Problem"
Any help I can get is appreciated
You have this
WebView wv = (WebView)findViewById(R.id.webView);
in fragment. findViewById is a method of your activity class.
I suggest you have webview in your fragment xml and use the below
WebView wv = (WebView)rootView.findViewById(R.id.webView);
Edit
Replace
WebView wv = (WebView)rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.stackoverflow.com");
BY
WebView wv = (WebView)rootView.findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("http://www.stackoverflow.com");

Categories