I am new to Android and exploring it at the moment.
I have two Image Buttons which have to load different activities onClick.
ImageButton btn1= (ImageButton)findViewById(R.id.timetable);
btn1.setOnClickListener(btnListener1);
ImageButton btn2= (ImageButton)findViewById(R.id.location);
btn2.setOnClickListener(btnListener2);
private OnClickListener btnListener1 = new OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(getBaseContext(), HelloWorld1.class);
startActivity(myIntent);
}
};
private OnClickListener btnListener2 = new OnClickListener()
{
public void onClick(View view)
{
Intent myIntent2 = new Intent(getBaseContext(), HelloWorld2.class);
startActivity(myIntent2);
}
};
//my manifest ......
<activity android:name="myApp" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".HelloWorld1"></activity>
<activity android:name=".HelloWorld2"></activity>
//and my main.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="#+id/widget34"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#ffffff"
>
<GridView
android:id="#+id/widget36"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="2"
android:layout_x="110px"
android:layout_y="32px"
android:layout_centerInParent="true">
</GridView>
<ImageButton
android:id="#+id/timetable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="210px"
android:layout_y="142px"
android:background="#drawable/icon2">
</ImageButton>
<ImageButton
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="100px"
android:layout_y="342px"
android:background="#drawable/icon">
</ImageButton>
This code causes errors, could anyone point where I am going wrong please.
Many thanks in advance.
Let's put aside the finish() method since i dont know what the heck it's doing there :)
Case1: Look careful at your activity xml view file, you might accidentally define your button as Button instead of ImageButton -> Error
Case2: dont use view.getContext(), instead use getBaseContext() or getApplicationContext()
You are calling startActivityForResult() and then immediately calling finish(). Where is the result going to go if the activity is finished?
What behavior do you want and what are you getting instead. The more specific you can be, the better the quality of help you will get.
Try to write something simillar like code below. You can also define first function which will create new activity when button will be pressed.
public class HelloAndroid extends Activity {
private Button button_1;
private Button button_2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialiyeFields();
}
private void initialiyeFields(){
button_1 = (Button)findViewById(R.id.button1);
button_1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HelloAndroid.this, HelloWord1.class);
startActivity(intent);
}
});
button_2 = (Button)findViewById(R.id.button2);
button_2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HelloAndroid.this, HelloWord2.class);
startActivity(intent);
}
});
}
}
Related
have 4 activity : Main Activity,p1,p2,p3
my resume button not working . i want when i click in resume button app open my last activity .
for example : when in p2 click go to main , then in main when click resume , p2 open . here is my code :
Main Activity :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
Button resume = (Button) findViewById(R.id.resume);
Button next = (Button) findViewById(R.id.next);
Button exit = (Button) findViewById(R.id.exit);
resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences myPref = getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
String lastActivity= myPref.getString("lastactivity","");
try {
Intent fooActivity = new Intent(MainActivity.this,Class.forName(lastActivity));
startActivity(fooActivity);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, p1.class);
startActivity(intent);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
}
}
XML layout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="resume"
android:layout_width="wrap_content"
android:id="#+id/resume"
android:layout_height="wrap_content" />
<Button
android:text="next"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="exit"/>
</LinearLayout>
p1 :
public class p1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.p1);
Button next = (Button) findViewById(R.id.next);
Button home=(Button)findViewById(R.id.home);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, p2.class);
startActivity(intent);
}
});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, MainActivity.class);
startActivity(intent);
}
});
}
private void storeCurrentActivity(){
SharedPreferences myPref =getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myPref.edit();
editor.putString("lastactivity", this.getClass().getSimpleName());
editor.commit();
}
#Override
public void onResume(){
super.onResume();
storeCurrentActivity();
}
}
XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="page 1"/>
<Button
android:text="go in main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home"/>
</LinearLayout>
and p2,p3 like p1
and this my manifast :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.er.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".p1"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".p2"
android:label="#string/title_activity_p2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".p3"
android:label="#string/title_activity_p3"
android:theme="#style/AppTheme.NoActionBar"/>
</application>
</manifest>
you have to do below things to achieve what you want
whenever you open activity you have to save previous activity name in prefrance.
when you press resume button get activity name from prefrance and open activity using below code
Intent intent = new Intent();
intent.setClassName("com.android.browser","com.android.BrowserActivity");
context.startActivity(intent);
// clear previous activity before start
when you app relaunch app then do step 2 again in main Activity
in this type of approch you have to maintain flow of application using singletone or clear stack before launch activity. because you have to handle backbutton
I'd seen this asked in many, many places and have tried to follow the instructions given to no avail. I dont know if the questions are old, i'm doing things incorrectly or if my android studio program isnt working. What i want to do is to only open a new activity when a button is clicked. I'm very new to developing android applications.
I've recently tried to follow the answer provided here: How do I get a button to open another activity in Android Studio?
OnClick on the button is called "goTutorials"
My original activity is called home (Not mainActivity)
The new one is called tutorials.
This is what i added from trying to follow the link above:
In home's java file:
btn = (Button)findViewById(R.id.open_activity_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(home.this, tutorials.class));
}
});
In manifest file:
<activity
android:name="tutorials"
android:label="#string/app_name">
</activity>
Method 1
Use the onclick attribute in XML (so that whenever you click the button, defined method will trigger)
Step 1. - go to the XML where you button is(activity_home) & add
<Button
............
android:onClick="gotoTutorial"/>
Step 2. - then go to the home.Java & add following
public void gotoTutorial(View v){
Intent tutorialPage = new Intent (this, tutorials.class);
startActivity(tutorialPage);
}
Method 2
Use the setOnClickListener
Step 1. -
//create the link to the button in the interface
btn_tutorial = (Button)findViewById(R.id.tutorial_button);
btn_tutorial.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent tutorialPage = new Intent (this, tutorials.class);
startActivity(tutorialPage);
}
}
I have created a sample app please see the code below.
You need to specify information of all activities in Manifest file.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nextech.startnewactivity">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TutorialsActivity"
android:label="#string/title_activity_tutorials"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
My Launcher activity is MainActivity.java
package com.nextech.startnewactivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startTutorials = (Button)findViewById(R.id.startTutorials);
startTutorials.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent tutorialsActivityIntent = new Intent(MainActivity.this,TutorialsActivity.class);
MainActivity.this.startActivity(tutorialsActivityIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.nextech.startnewactivity.MainActivity"
tools:showIn="#layout/activity_main">
<TextView android:id="#+id/welcomeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_centerHorizontal="true"
android:text="Hello World! This is main activity!" />
<Button android:id="#+id/startTutorials"
android:layout_below="#+id/welcomeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Start Tutorials"/>
</RelativeLayout>
TutorialsActivity.java
package com.nextech.startnewactivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class TutorialsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorials);
}
}
activity_tutorials.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.nextech.startnewactivity.TutorialsActivity"
tools:showIn="#layout/activity_tutorials">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is tutorial activity"
android:layout_centerInParent="true"/>
</RelativeLayout>
I hope it helps.
Your manifest file is not displaying, but make sure you add the activity in your manifest AndroidManifest.xml in the application field. Here's an example from Google: Link
<application ... >
...
<activity
android:name="com.mycompany.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.mycompany.myfirstapp.MyActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.mycompany.myfirstapp.MyActivity" />
</activity>
Otherwise, the method you're using should be correct. You create an intent to the class of the Activity you want to start.
Intent intent = new Intent(this, tutorials.class);
startActivity(intent);
Make sure you have the necessary methods such as onCreate(Bundle savedInstance) Overrided.
Note that in the sample above android:name="" is your activity's full path name to the class (without .class/.java) and label is going to be the action toolbar string you'll see. In the <meta-data/> section you can alter the android:value="" to the starting activity's name so that will need to change based on what you call it.
Finally, make sure it has an XML view to go with it, as it gets inflated in the onCreate(Bundle savedInstance) call.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_here);
}
inside your activity file write this
Button btn = (Button)findViewById(R.id.open_activity_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(home.this, tutorials.class));
}
});
XML
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
.Java class
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, YourActivityYouWantToOpen.class);
startActivity(intent);
}
I have two buttons (start/stop) that when clicked need to have a Toast pop up saying what has happened to the Service. Start = popup of "service has started" and the service actually starts. The service isn't finished and will be grabbing some GPS info later on.
Anyway, none of my Toasts show up and I'm hoping I'm not missing something obvious.
Main (Activity)
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startBtn = (Button) findViewById(R.id.startButton);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), ParseService.class));
}
});
Button stopBtn = (Button) findViewById(R.id.startButton);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), ParseService.class));
}
});
}
}
ParseService
public class ParseService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent e, int flags, int startId){
Toast.makeText(this, "Service has Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "Service has Stopped", Toast.LENGTH_LONG).show();
}
}
activity_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"
android:textAlignment="center"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/startButton"
android:layout_width="150dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="92dp"
android:text="Start" />
<Button
android:id="#+id/stopButton"
android:layout_width="150dp"
android:layout_height="60dp"
android:layout_alignLeft="#+id/startButton"
android:layout_below="#+id/startButton"
android:layout_marginTop="74dp"
android:text="Stop" />
</RelativeLayout>
You are supposed to use the Application's Context from a Service and not the Service's Context.
From your Service:
Toast.makeText(getApplicationContext(), // application Context not 'this'
"Service has Started",
Toast.LENGTH_LONG).show();
Alternatively, you could display them from your Activity before you invoke the Service if you wish but I think where you have the calls currently positioned makes more sense and would reduce repetition later on as long as you always want the Toast displayed.
EDIT:
Ok, after making a quick test app I think I found what might be going wrong for you.
Do you have the Service declared in your AndroidManifest.xml??
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.indivisible.testapp">
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".toasts.ToastActivity"
android:label="#string/title_activity_toast">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Define your Service as below.
In my case the path is:
.../TestApp/app/src/main/java/com/indivisible/testapp/toasts/ToastService.java
Android Studio has a nice auto-complete when you press '.'
-->
<service
android:name=".toasts.ToastService"
android:label="ToastService">
</service>
</application>
</manifest>
It seems like your service is not getting started, make sure the service is declared in the manifest and enabled as below:
<service
android:name=".ParseService"
android:enabled="true" />
Hope this helps
When I go to install the app on the device, I click the button but nothing happen.
I want to make device play tosse.acc from res/raw when I click the button...
Ok resolved the problem :) thanks for answers guys :D ( i have changed the name of the song from tosse to toxxe)
public void tosse1(View v) {
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.toxxe);
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Resume the music player
mp.start();
}
});
}
Here my code:
public void tosse1(View v) {
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.tosse);
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Resume the music player
mp.start();
}
});
}
activity_main:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.tosseapp.app.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="tosse1" />
</RelativeLayout>
AndroidManifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<activity
android:name="com.example.tosseapp.app.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Declare your mp as private variable in your class:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.tosse);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Try getting a Mediaplayer Instance like this:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.tosse);
should solve your problem, because it also prepares the MediaPlayer, see documentation:
public static MediaPlayer create (Context context, int resid) Added in API level 1
Convenience method to create a MediaPlayer for a given
resource id. On success, prepare() will already have been called and
must not be called again.
When done with the MediaPlayer, you should call release(), to free the
resources. If not released, too many MediaPlayer instances will result
in an exception.
i have develop one android application.
Here i have to set the tabbar bottom on all android activities.how can i do.please give me solution for these.
i have totally 10 activities means the tabbar is show on botton on all 10 activities.how can i do in android.please help me.
These is my 1st activity:
setContentView(R.layout.tabbar);
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
TabSpec dbspec = tabHost.newTabSpec("Home");
dbspec.setIndicator("Home", getResources().getDrawable(R.drawable.home));
Intent dbIntent = new Intent(this, MainActivity.class);
dbspec.setContent(dbIntent);
tabHost.addTab(dbspec);
TabSpec orderspec = tabHost.newTabSpec("Cart");
orderspec.setIndicator("Cart", getResources().getDrawable(R.drawable.cart));
Intent orderIntent = new Intent(this, ViewCartActivity.class);
orderspec.setContent(orderIntent);
tabHost.addTab(orderspec);
TabSpec settingspec = tabHost.newTabSpec("My Account");
settingspec.setIndicator("My Account", getResources().getDrawable(R.drawable.myaccount));
Intent settingIntent = new Intent(this, CustomerLogin.class);
settingspec.setContent(settingIntent);
tabHost.addTab(settingspec);
tabbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/linearLayout1"
android:layout_height="match_parent">
<TabWidget
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/tabs"
android:layout_alignParentBottom="true">
</TabWidget>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/tabcontent">
</FrameLayout>
</RelativeLayout>
</TabHost>
In first tab have to perform MainActivity(GridView) activity.it is woked well.in Main activity i have to clik any item means it is go to SubCate(listview) activity.Here also i have to display tabbar on bottom.how can i set.
In subcate.xml file have included below code:
<include
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
layout="#layout/tabbar" />
but the tabbar is not display.whats wrong here.please help me.
Please write below code instead of your code for add multiple activities in one TabActivity, it will solve your problem.
ActivityStack.java
public class ActivityStack extends ActivityGroup {
private Stack<String> stack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null)
stack = new Stack<String>();
// start default activity
push("FirstStackActivity", new Intent(this, Tab_SampleActivity.class));
}
#Override
public void finishFromChild(Activity child) {
pop();
}
#Override
public void onBackPressed() {
pop();
}
public void push(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
stack.push(id);
setContentView(window.getDecorView());
}
}
public void pop() {
if (stack.size() == 1)
finish();
LocalActivityManager manager = getLocalActivityManager();
manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent();
Window newWindow = manager.startActivity(stack.peek(), lastIntent);
setContentView(newWindow.getDecorView());
}
}
}
TabActivity.java
public class TabActivity extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_screen);
TabHost tabHost = getTabHost();
Intent intent = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.home));
spec.setContent(intent);
tabHost.addTab(spec);
Intent intent1 = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec1 = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.invoice));
spec1.setContent(intent1);
tabHost.addTab(spec1);
tabHost.setCurrentTab(0);
}
}
FirstActivity.java
public class FirstActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("Tab Sample Activity ");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), SecondActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("SecondActivity", intent);
}
});
setContentView(textView);
}
}
SecondActivity.java
public class SecondActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("First Stack Activity ");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), ThirdActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("ThirdActivity", intent);
}
});
setContentView(textView);
}
}
ThirdActivity.java
public class ThirdActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Add Below XML files into your res/layout folder.
1) tab_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="3dp" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#android:id/tabs"
android:layout_weight="1" />
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</TabHost>
2) 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:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
AndroidManifest.xml:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.tabsample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".TabActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ActivityStack"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ThirdActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
And see below link for more information on add multiple activities under one TabActivity with complete example.
Android - Multiple Android Activities under one TabActivity
You can use this class for implementing the functionality you have specified.
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
public class TabActivityGroup extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null)
mIdList = new ArrayList<String>();
}
/**
* This is called when a child activity of this one calls its finish method.
* This implementation calls {#link LocalActivityManager#destroyActivity} on
* the child activity and starts the previous activity. If the last child
* activity just called finish(),this activity (the parent), calls finish to
* finish the entire group.
*/
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size() - 1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index);
index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
/**
* Starts an Activity as a child Activity to this.
*
* #param Id
* Unique identifier of the activity to be started.
* #param intent
* The Intent describing the activity to be started.
* #throws android.content.ActivityNotFoundException.
*/
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
/**
* The primary purpose is to prevent systems before
* android.os.Build.VERSION_CODES.ECLAIR from calling their default
* KeyEvent.KEYCODE_BACK during onKeyDown.
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// preventing default implementation previous to
// android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Overrides the default implementation for KeyEvent.KEYCODE_BACK so that
* all systems call onBackPressed().
*/
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* If a Child Activity handles KeyEvent.KEYCODE_BACK. Simply override and
* add this method.
*/
#Override
public void onBackPressed() {
int length = mIdList.size();
if (length > 1) {
Activity current = getLocalActivityManager().getActivity(
mIdList.get(length - 1));
current.finish();
}
}
}
Create an intermediate activity as below by extending TabActivitygroup
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class InterMediateActivity extends TabActivityGroup{
String TabID;
String TabName;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TabID=getIntent().getStringExtra("TabID");
TabName=getIntent().getStringExtra("TabName");
Log.i("Tab from intermediate",""+TabID+" "+TabName);
filterTabs(TabID);
}
private void filterTabs(String TabID)
{
if(TabID.trim().equals("Home"))
{
startChildActivity("Options", new Intent(this,HomePage.class));
//TabsUtil.setTabIndicator(specTab,"Wall", null, tabView);
}
if(TabID.trim().equals("Menu"))
{
startChildActivity("Options", new Intent(this,MenuPage.class));
//TabsUtil.setTabIndicator(specTab,"Wall", null, tabView);
}
if(TabID.trim().equals("Gallery"))
{
Log.i("GALLERY check", "gallery check");
startChildActivity("Options", new Intent(this,GalleryPage.class));
}
if(TabID.trim().equals("Aboutus"))
{
startChildActivity("Options", new Intent(this,AboutUsPage.class));
}
if(TabID.trim().equals("Location"))
{
startChildActivity("Options", new Intent(this,LocationList.class));
}
if(TabID.trim().equals("Events"))
{
startChildActivity("Options", new Intent(this,EventsPage.class));
}
if(TabID.trim().equals("TipCalculator"))
{
startChildActivity("Options", new Intent(this,TipCalculatorPage.class));
}
if(TabID.trim().equals("Special"))
{
startChildActivity("Options", new Intent(this,SpecialPage.class));
}
if(TabID.trim().equals("NowRunning"))
{
startChildActivity("Options", new Intent(this,NowRunningPage.class));
}
if(TabID.trim().equals("ShowTimes"))
{
startChildActivity("Options", new Intent(this,ShowTimePage.class));
}
if(TabID.trim().equals("GpsCoupon"))
{
startChildActivity("Options", new Intent(this,GPSCouponPage.class));
}
if(TabID.trim().equals("UpcomingMovieNames"))
{
startChildActivity("Options", new Intent(this,UpcomingPage.class));
}
if(TabID.trim().equals("PriceListOfServices"))
{
startChildActivity("Options", new Intent(this,ServicesPage.class));
}
if(TabID.trim().trim().equals("NewsLetter"))
{
Log.i("newsletter check", "newsletter check");
startChildActivity("Options", new Intent(this,NewsLetter.class));
}
if(TabID.trim().trim().equals("Website"))
{
startChildActivity("Options", new Intent(this,WebSitePage.class));
}
}
}
And instead of setting the tabs from tabactivity directly you can set them inside the intermediate activity. Then call the Intermediate activity from the tabactivity.
Intent intent = new Intent(this, InterMediateActivity.class);
intent.putExtra("TabID", item.elementAt(0));
intent.putExtra("TabName", item.elementAt(1));