NavigationView onClick from xml causes errors - android

Using NavigationView from the newly released Android support design library, if a navigation header layout includes an onClick (in the xml), onClick event crashes app. OnClick can be added programmatically via view.onClickListener (instead of xml), and then clicking works fine. But for some reason, whenever xml onClick is used, there is an error.
Here's my main layout:
<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/mainActivityLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/mainContentFrame"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/drawerNavView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
In my activity, my menu item clicks (added with navView.setNavigationItemSelectedListener()) work fine. The problem is when the header is clicked:
drawer_header.xml:
...
<View
android:id="#+id/testButton"
android:layout_width="match_parent"
android:layout_height="60dp"
android:onClick="testButtonClick"/>
...
Produces the following error:
java.lang.IllegalStateException: Could not find a method testButtonClick(View)
in the activity class android.view.ContextThemeWrapper for onClick handler
on view class android.view.View with id 'testButton'
UPDATE
NavigationView can use standard Menu resource files, but there is a similar problem if using onClick from the menu XML resource. According to the Menu Resource reference, the android:onClick attribute overrides the normal callbacks. This usually works fine, but with menu items in NavigationView, it doesn't. Instead, it crashes with this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}:
android.view.InflateException: Binary XML file line #34:
Error inflating class android.support.design.widget.NavigationView
The error goes away when I remove the XML onClick.
UPDATE
I tested xml onClick using the "official" demo project for the Android Design Library. Same results: adding onClick (in xml) to a NavigationView's menu or header causes the app the crash. So this appears to be a bug with NavigationView.
RESOLVED IN v23.1
Google released a fix for these XML onClick errors in Support Library v23.1.

Confirmed, this is a bug in the support library.
Apparently it's related to ContextThemeWrapper, and according to this bug report, the problem exists in Support Library 22.1.
So, the short answer is:
Don't use XML onClick with NavigationView (or some other components like EditText), until it's fixed.
Workaround:
Set click listeners in code. For NavigationView, use setNavigationItemSelectedListener().
UPDATE: This bug has ben fixed
You can now use XML onClick in Support Library 23.1 (bug report). I've verified it works in my app. But there seems to be other (newer) XML issues with NavView in v23.1 (see below), even though this particular onClick error is now fixed.
For completeness:
There appears to be another (related?) bug when inflating NavigationView header via XML. Using XML app:headerLayout produces errors with 23.1, even though XML onClick now works. Because of this inflation issue, you'll need to use NavigationView.inflateHeaderView() method in code. This new method was added in 23.1 and, apparently, the previous XML inflate is now broken (or maybe they deprecated app:headerLayout without telling anyone?). More info detailed here.

Hi: my solution is remove
app:headerLayout="#layout/drawer_header"
from your NavigationView layout as below:
<android.support.design.widget.NavigationView
android:id="#+id/drawerNavView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
And then use below in your activity or view controller
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView= navigationView.inflateHeaderView(R.layout.nav_header);
TextView tvName = (TextView) headerView.findViewById(R.id.id_nav_header_uname);
tvName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
L.d("=======tv click=====");
}
});
this works for me.

You may write your method in code without mentioning it in XML. In code you just use the code
public void methodName()
{
//
}
View v = findViewById(R.id.view_id);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
methodName();
}
});

NavigationView has an OnNavigationItemSelectedListener for the Menu Items.
e.g.
navigationView.setNavigationItemSelectedListener(new SelectedNavigationItemListener());
private class SelectedNavigationItemListener implements NavigationView.OnNavigationItemSelectedListener {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()){
case id1:
break;
}
Log.d("MENU ITEM", menuItem.getTitle().toString());
return false;
}
}
For the Header you can do something like this e.g
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View header = navigationView.inflateHeaderView(R.layout.drawer_header);
RelativeLayout drawerHeader = (RelativeLayout) header.findViewById(R.id.drawerHeader);
drawerHeader.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("CLICKED HEADER", "Header Clicked");
}
});
Reference for my HeaderLayout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerHeader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textSize="16sp" />

Related

Can not resolve R.id.toolbar

I'm dipping my toes into Android Development by following along examples from this book. I am unable to get the example below to work, though. Instructions are: 1) New project named Dialog 2) Empty Activity 3) Paste/edit to look like the code below.
The message is that Studio can't resolve: R.id.toolbar, R.id.fab, R.menu, and R.id.action_settings.
I'm running Android Studio 3.1.3 on macOS High Sierra. My best guess is that that either the instructions are missing steps or since the book is ~2 years old Android Studio has changed behavior causing this example to break. I don't know enough about this development process to even know how to start to diagnose this.
In AndroidManifest.xml add this line to the activity block:
android:theme="#style/Theme.AppCompat.Dialog"
And this is the only code file to change (DialogActivity.java) for the project:
package com.example.sample.dialog;
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.View;
import android.view.Menu;
import android.view.MenuItem;
public class DialogActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with an action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_dialog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_dialog.xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DialogActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
The reason you are getting those errors is because Java is looking for references in XML that have not been created. For example, it is looking for a reference called "R.id.fab" which was never created.
To fix this, you are going to have to go into the res folder and create the necessary files. Inside of the res -> layout -> "activity_dialog.xml" file, you will have to create a FAB in order to get rid of that error. You can copy/paste this code.
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"/>
Here, I create the necessary View in XML, and give it an id called fab so you can reference it in the java code. You will also need to create a menu folder and file, so to do that right click on the res folder, and go to "new Android Resource File". Set the file name to "menu" and the resource type should also be menu. Then when you hit "OK", you will see a new folder called menu, and inside of that a file called "menu.xml".
Inside that "menu.xml" file, you're going to have to create your menu options with an id of "action_settings". You can do that by using the code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_settings" android:title="Settings"/>
</menu>
Lastly, you can create your toolbar by right clicking on the layout folder and selecting new layout resource file. You can name it 'toolbar', and set the root element to android.support.v7.widget.Toolbar. This will generate the appropriate code for you, and you can edit it however you'd like. After that go back into the "activity_dialog.xml" file and use this code:
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
This should get rid of all 4 errors
Double check the id's in the R.layout.activity_dialog file. Android studio will output that message when the id that you are looking for is not found in the inflated layout.
EDIT:
You do not have a Toolbar declared in your XML file. When you want to search for a layout element to use in a Fragment or Activity, you use the id parameter you set in the XML file. If you forget to set the id or use the wrong id, it will tell you that the symbol cannot be resolved. There are too many items to add to your code, but follow the links below and you'll pick it up quickly enough. Let me know if you need more information. Also, CodePath is an excellent resource that I heavily relied on when I started learning Android development.
Look at this for a tutorial for adding a toolbar to a layout file and this for more miscellaneous information.
You have not gotten a reference to the view from the xml.
Get the reference from the xml for example if have a button defined in xml with an id of myBtn i would get the reference as Button button = findViewById(R.id.myBtn).
On the main menu, choose File. Invalidate Caches/Restart. The Invalidate Caches message appears informing you that the caches will be invalidated and rebuilt on the next start. Use buttons in the dialog to invalidate caches.

How to access an element from an <include> layout file which is inside not an activity but a fragment?

Just wondering if any of you guys could help me to access an element from an 'include' layout file which is inside not an activity but a fragment?
Most posts tell me to do something like that:
How to access Button inside "include" layout but as I am not on an activity the listener for the image won't work.
Ps: The listener works (opens the nav drawer) when I call an element which is not in the include file but on the fragment layout.
That's what I have inside the onCreateView method for my fragment:
View myLayout = view.findViewById(R.id.layout_top_bar);
image = (ImageView) myLayout.findViewById(R.id.image_left_top_bar);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity mainActivity = (MainActivity)getActivity();
mainActivity.openMenuDrawer();
}
});
That's my include layout file:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_top_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<ImageView
android:id="#+id/image_left_top_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/hamburger_icon" />
And that's how I'm including it within the fragment layout file:
<include layout="#layout/top_bar" />
Thanks very much for any help on that! :)
You can access it directly with the root layout of your fragment like this.
image = view.findViewById(R.id.image_left_top_bar);
In case we are adding the layout dynamically by inflating it, we use the approach you mentioned above but that's not needed here.
Put a id to the Layout and later access to the elemento.
View myLayout = findViewById( R.id.layout );
View myView = myLayout.findViewById( R.id.item );
Change:
getLayoutPosition()
For
getAdapterPosition()

Google Android tutorial - not compiling

I did everything just as stated in this tutorial:
google android basic tutorial
and despite everything being done just as described, the code refuses to compile with 3 errors. Looks like the guys writing the turorial forgot to mention what are those things and where/how do I define them.
The errors I get:
Error:(24, 68) error: cannot find symbol variable container
Error:(36, 23) error: cannot find symbol variable action_settings
Error:(46, 54) error: cannot find symbol variable fragment_display_message
Neither of the 3 fields are defined anywhere (Perhaps one of the libraries is wrong?)
The file in question is:
package com.example.asteroth.first;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.TextView;
import android.R;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
// setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message, container, false);
return rootView;
}
}
}
I am using Android Studio I just downloaded and no question from search or Similar Questions points at the problem like this one, hence I suspect authors of tutorial forgot to mention something minor. I've seen suggestion to place the "container" as a new ID in one of the XML files, but to no avail.
EDIT:
'cannot find symbol ActionBarActivity' following Android Development Tutorial?
This post suggest a solution, however it changes ActionBarActivity to just Activity which is very different from what the tutorial uses and I don't know how serious repercussions would it cause
EDIT2:
Problems found and removed:
import android.R //causes action_settings error
container missing //had to add it in the xml file as an id
xml file named wrong //If I got that correctly, I'm still waiting for someone experienced to clarify, but seems like the tutorial used different name for the xml file then the one that the java code references
Remaining problem is similar to this one
Cannot resolve method placeholderfragment error
however, I both extend Fragment and include android.app.Fragment as can be seen in the included file.
I tried the same tutorial and here is how I fixed my errors:
R.id.container cannot be resolved error
I had to import android.support.v4.app.Fragment to fix this problem and add android:id = "#+id/container" to the RelativeLayout section in my activity_display_message.xml file.
fragment_display_message cannot be resolved error
Change R.layout.fragment_display_message to R.layout.activity_display_message instead. There is no need for creating a new xml file for fragment_display_message.
This should fix these two errors.
But you would probably be better off if you comment out the if(savedInstanceState............ statement as otherwise your program would crash once you try to run it if it doesn't give you any errors.
Your onCreate method should look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_display_message);
Intent intent=getIntent();
String message=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView=new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
/*if (savedInstanceState==null){
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}*/
}
I'm doing the tutorial for the first time now on Feb. 23, 2015 and ran into this compilation error though I feel like I've closely followed the steps. I changed fragment_display_message to activity_display_message which is an XML file they have us create in the tutorial. This seems to solve the error, and allow the app to run.
// A placeholder fragment containing a simple view.
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_display_message,
container, false);
return rootView;
}
}
Add this line to take care of your first error: android:id = "#+id/container"
You get that error because container isn't in the XML.
Add <string name="action_settings">Action Settings</string>so that the "Action settings" which I'm assuming doesn't exist in your XML code since you have that error.
Create your own XML file with this exact name fragment_display_message.xmlto handle that error and check what code you might need to insert into it in your google tutorial. Often times with Eclipse, these files are not included for reasons outside my knowledge. So you have to create them or insert them yourself. (Make sure you have the latest version of the SDK by the way.
EDIT: Be sure to have the correct imports matching with your "tutorial". I took a gander at it and see you missing two imports. One of which another user answered.
It's a copy paste error.
If you paste code with "R." in it, the development environment always imports the android.R:
import android.R;
If you use R.id.... it is always looking up the android.R and not your own generated R class.
Delete the import and it should be fine. This general works for me.
After that you have to check if you already defined the id's and layout.
You can check Layouts by looking on the package explorer under res->layout. In your example there has to be an fragment_display_message.xml in it.
For id's you have to look up all of your layouts and check if there are the specific views like the container.
I got a similar error on the Building a Simple User Interface step:
Error:(18, 54) error: cannot find symbol variable toolbar
I've narrowed the cause down to res/layout/activity_my.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="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send" />
The original version that did compile (but no button or text box) is:
<?xml version="1.0" encoding="utf-8"?>
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=".MyActivity">
<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>
<include layout="#layout/content_my" />
<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" />
fragment_display_message
Make sure you have a file named fragment_display_message.xml in your res/layout folder.
action_settings
Make sure you have that item in your menu.xml file in res/menu
<menu 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"
tools:context=
".MenuExampleActivity" >
<item
android:id="#+id/action_settings"
android:orderInCategory="1"
app:showAsAction="never"
android:title="My menu option"/>
</menu>
container
Make sure you have a layout (ex. RelativeLayout) with the id set to "container" in your activity_main.xml file in res/layout, given that it's the reference for the code to insert the fragment there.

Set contentDescription for ActionBar's up button

I'm trying to customize the "Navigate up" default contentDescription that is associated with the up button of the ActionBar (I'm using ActionBarSherlock).
From ActionBarView's source:
public void setHomeButtonEnabled(boolean enable) {
mHomeLayout.setEnabled(enable);
mHomeLayout.setFocusable(enable);
// Make sure the home button has an accurate content description for accessibility.
if (!enable) {
mHomeLayout.setContentDescription(null);
} else if ((mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
mHomeLayout.setContentDescription(mContext.getResources().getText(
R.string.abs__action_bar_up_description));
} else {
mHomeLayout.setContentDescription(mContext.getResources().getText(
R.string.abs__action_bar_home_description));
}
}
so the key would be how to get a reference to mHomeLayout. getWindow().getDecorView().findViewById(android.R.id.home) is not working, as it's returning an ImageView.
How could I do?
Thanks ;)
layout
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_scrollFlags="scroll|enterAlways">
</android.support.v7.widget.Toolbar>
code
public Toolbar toolbar;
...
setContentView(layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(layoutTitle);
setSupportActionBar(toolbar);
...
getSupportActionBar().setHomeActionContentDescription("Go Back To XYZ Screen");
In xml, use "navigationContentDescription"
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:layout_alignParentTop="true"
app:navigationContentDescription="#string/back"/>
Here how I can do what you need in a previous project :
((View) getWindow().getDecorView().findViewById(android.R.id.home).getParent().getParent()).setContentDescription("blablabla");
Using viewHierarchy plugin helps me to understand how ActionBar layout is build.
In case someone needs to set the ActionBar's home-button's content-description for UIAutomator, use
((View) getWindow().getDecorView().findViewById(android.R.id.home).getParent()).setContentDescription("MANUALLYSET-home-up");
and access the view in your UIAutomatorTestCase using
new UiObject(new UiSelector().description("MANUALLYSET-home-up").className("android.widget.FrameLayout"));
For some reason the additional *.getParent() did not work, instead Android uses some auto-generated content-description value for that parent which may differ in some Android versions (e.g. "app_name, Close navigation drawer" on KITKAT and "app_name, Navigate up" on JELLYBEAN). Accessing its child works too, fortunately.
Kind regards

Does Android Have MasterPage Concept like .NET or Tiles concept in Struts to add Header on all pages?

I am developing an Android Application. In this application, Logo bar is shown on all pages(Activities) or we can say it has header on all pages.
This Logo Bar have few icons like Home, Login, Notification, etc. and on Clicking on these icons corresponding navigation will perform.
for example if user is any where in application and click on home icon, he will navigate to the home page of application.
I am able to inflate logobar.XML into my All Activity by coding. but problem is i have to call onClickListener on all pages for all icons in Logo Bar.
This is not a good programming way.
How can i implement Logo Bar Activity in all other activity without repeating of code?
Is android have any Master Page concept as in .Net or tiles concept as in Struts?
Please guide me.
Edit: ok i got it. may be this answer will help you.
Try using Tab widget with tabactivity check this link for using fragment and tab http://developer.android.com/reference/android/app/TabActivity.html for android. i think for lower versions also we can use this. this si what the link says - "you can use the v4 support library which provides a version of the Fragment API that is compatible down to DONUT."
you have to create your masterLayout in xml and that you have to include it in your other
layouts in which you have to have it.
The solution was pretty easy.
You need to extends "Activity" Class,in onCreate function SetContentView to your base xml layout and also need to override setContentView in base Activity Class
For Example:
1.Create "base_layout.xml" with the below code
<?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:orientation="vertical"
android:background="#000000"
android:padding="15dp" >
<LinearLayout android:orientation="horizontal" android:background="#000000"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:minHeight="50dp" android:paddingLeft="10dp">
<ImageView android:layout_width="wrap_content" android:id="#+id/ImageView01"
android:adjustViewBounds="true" android:layout_height="wrap_content"
android:scaleType="fitCenter" android:maxHeight="50dp" />
</LinearLayout>
<LinearLayout android:id="#+id/linBase"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</LinearLayout>
</LinearLayout>
2.Create "BaseActivity.java"
public class BaseActivity extends Activity {
ImageView image;
LinearLayout linBase;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.base_layout);
image = (ImageView)findViewById(R.id.ImageView01);
image.setImageResource(R.drawable.header);
linBase = (LinearLayout)findViewById(R.id.linBase);
}
#Override
public void setContentView(int id) {
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(id, linBase);
}
}
and
public class SomeActivity extends BaseActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.some_layout);
//rest of code
}
}
The only thing I noticed so far was that when requesting a progress bar (requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) this needs to be done before calling super.onCreate. I think this is because nothing can be drawn yet before calling this function.
This worked great for me and hopefully you will find this useful in your own coding.
There is something like that, but only available on api 11+ (3.2 and Android 4.0.x Ice Cream Sandwich). Its called actionbar ( http://developer.android.com/reference/android/app/ActionBar.html).
I have done this using XML file.
I am just creating runtime view from XML file , and add it to the Activity layout.
I have created method for that
public static void setLoginview(Context ctx, RelativeLayout layout) {
LayoutInflater linflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = linflater.inflate(R.layout.loginheader, null);
layout.addView(myView);
try {
layout.getChildAt(0).setPadding(0, 50, 0, 0);
} catch (Exception e) {
}
}
ctx is the application contetx and layout is the layout in which i want to add that view.

Categories

Resources