I'm doing this tutorial, but I'm having some trouble with understanding how to make this into one activity. (In the tutorial, you would have Main Activity and Display Message Activity, but for my purposes, I need it to be in one activity) I understand how everything works, but I just can't figure out how to make this into one activity. Any help is appreciated!
Here is the tutorial I'm working on: https://developer.android.com/training/basics/firstapp/building-ui.html
And I'll include my code below, but it's probably easier to see where I am in the tutorial (I'm at the step, "Starting Another Activity").
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: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"
android:onClick="sendMessage" />
</LinearLayout>
MainActivity.java
package com.example.helloworld;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.content.Intent;
import android.os.Build;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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);
}
/**
* 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.fragment_main, container, false);
return rootView;
}
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
If you want to change the layout when a button is pressed and display hello world you can use your fragment PlaceholderFragment inside your MainActivity to display it
sample:
public void sendMessage(View view) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Fragment:
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_main, container, false);
TextView tx = (TextView)rootView.findViewById(R.id.hello_world);
tx.setText(editText.getText().toString());
return rootView;
}
}
In your fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/start_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Related
I'm using fragment tab.
I need the webView to refresh to the original url when user clicks on the title.
This is my code for now.
MainActivity.java
package com.cn1304w.munch;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
#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);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#fff"
android:paddingBottom="10dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="10dp"
android:textColor="#000" />
</android.support.v4.view.ViewPager>
ViewPagerAdapter.java
package com.cn1304w.munch;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "Home", "Search", "Profile" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
FragmentTab3 fragmenttab3 = new FragmentTab3();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
fragmenttab1.java
package com.cn1304w.munch;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class FragmentTab1 extends Fragment {
WebView webView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get the url to open
// set up the WebView
webView = (WebView) getView().findViewById(R.id.webView);
webView.setWebViewClient(new MyBrowser());
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadUrl("http://192.168.1.4/index.html");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragmenttab1, container, false);
return view;
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
fragmenttab1.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" >
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
Use this functionality when ever you need to refresh your webview.
ourActivity.this.webView.loadUrl("http://www.mysite.php");
I am new to android.. in a video tutorial I watch the guy writing a code and compiling it with no any error.. but when the same code I type gives me error.. don't know why..
Well.. Layout xml file is ok.. there is a error in java file.. whenever I add to a onclicklistener method to a button... it does not give any error in the code section but when I compile it it shows an error.. that application XXX has stopped unexpectedly. pleas try again.
code is here..
package com.abrosoft.trycommand;
import java.util.Random;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
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.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import android.view.View.OnClickListener;
public class MainActivity extends ActionBarActivity {
EditText input;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Button cmd = (Button) findViewById(R.id.bCmd);
display = (TextView) findViewById(R.id.tvcmd);
input = (EditText) findViewById(R.id.etinput);
//if I delete this SetOnClickListener method.. it runs ok..
//I get xml layout on screen of emulator.. but with this method..it doesnot run
cmd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//even I write any lines of code which should perform any action on button
//click is giving same error
}
});
}
#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);
}
/**
* 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.fragment_main, container, false);
return rootView;
}
}
}
here is my xml file code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="25dp"
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.abrosoft.trycommand.MainActivity$PlaceholderFragment" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="type a command"
android:id="#+id/etinput"
android:inputType="text"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/bCmd"
android:layout_weight="50"
android:text="Command"
/>
<ToggleButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tgB"
android:layout_weight="50"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/tvcmd"
/>
thanks in advance
Remove the condition
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Also remove the PlaceHolder Class
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_main, container, false);
return rootView;
}
and change the setContentView() method of OnCreate(Bundle savedInstances) to
setContentView(R.layout.fragment_main);
Just Comment the below section in your code and then try to run.
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
remove this
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
from the onCreate(Bundle) method.
It will help
Put below code inside onCreateView
Button cmd = (Button) findViewById(R.id.bCmd);
display = (TextView) findViewById(R.id.tvcmd);
input = (EditText) findViewById(R.id.etinput);
//if I delete this SetOnClickListener method.. it runs ok..
//I get xml layout on screen of emulator.. but with this method..it doesnot run
cmd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//even I write any lines of code which should perform any action on button
//click is giving same error
}
});
Change onCreateView to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button cmd = (Button) rootView.findViewById(R.id.bCmd);
display = (TextView) rootView.findViewById(R.id.tvcmd);
input = (EditText) rootView.findViewById(R.id.etinput);
//if I delete this SetOnClickListener method.. it runs ok..
//I get xml layout on screen of emulator.. but with this method..it doesnot run
cmd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//even I write any lines of code which should perform any action on button
//click is giving same error
}
});
return rootView;
}
I am currently just starting to learn android development and have created a basic "Hello world" app that uses "activity_main.xml" for the default layout. I tried to create a new layout xml file called "new_layout.xml" with a text view, a text field and a button and did the following changes in the MainActivity.java file:
setContentView(R.layout.new_layout);
I did nothing else expect for adding a new_layout.xml in the res/layout folder, I have tried restarting and cleaning the project but nothing. Below is my activity_main.xml file, new_layout.xml file and MainActivity.java
activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.example.androidsdk.demo.MainActivity"
tools:ignore="MergeRootFrame" />
new_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
MainActivity.java file
package org.example.androidsdk.demo;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_layout);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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);
}
/**
* 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.fragment_main, container, false);
return rootView;
}
}
}
Your new_layout.xml does not have a ViewGroup with the id container to which you add/replace Fragments.
.add(R.id.container, new PlaceholderFragment())
If you set activity_main.xml you had a FrameLayout with the id android:id="#+id/container" to which you add the Fragment PlaceHolderFragment.
You Either get rid of
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Or add a ViewGroup in new_layout.xml. Also have views in fragment layout and initialize them in onCreateView of Fragment. You are encouraged to use Fragments.
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
Edit: I changed my content view to setContentView(R.layout.fragment_main); the application still crashes. I do not quite understand the reason for this.
This is a simple application for detecting and counting the number of potholes felt on a road. I have read many threads on this issue and implemented many different changes to my code. But none seem to work out in fixing the error that I have. Where exactly am I going wrong in my code here?
MainActivity.java
package com.example.potholedetector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements Button.OnClickListener {
// Private member field to keep track of the number of potholes
private static int num_potholes = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
//Restore any saved state
super.onCreate(savedInstanceState);
//Set content view
setContentView(R.layout.activity_main);
//Initialize UI elements
final Button pothole = (Button)findViewById(R.id.pothole);
final TextView NumPotholes = (TextView)findViewById(R.id.NumPotholes);
//Link UI elements to actions in code
pothole.setOnClickListener(new Button.OnClickListener()
{
#Override
public void onClick(View v)
{
num_potholes++;
NumPotholes.setText("Number of potholes felt: " + num_potholes);
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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);
}
/**
* 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.fragment_main, container, false);
return rootView;
/** Called when the user clicks the Pothole button */
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
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.potholedetector.MainActivity$PlaceholderFragment" >
<TextView android:id="#+id/pothole_message"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="#string/pothole_message"
android:textSize="20sp"/>
<Button android:id="#+id/pothole"
android:layout_width="wrap_content"
android:minWidth="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/pothole"
android:onClick="potholeFelt"/>
<TextView android:id="#+id/NumPotholes"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:textSize="20sp"/>
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">PotholeDetector</string>
<string name="pothole_message">Pothole felt?</string>
<string name="pothole">Pothole</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
I tried to carefully follow many tutorials, but after spending so much time debugging, I am no closer to eradicating the error and moving on. How can I make this code work?
Your app is crashing for NPE, since you are passing as parameter R.layout.activity_main to setContentView, but the elements you are looking for are declared inside fragment_main.xml. Call setContentView(R.layout.fragment_main);
I have a very simple app which is just an activity with a tab view on it.
I have initialised and casted everything to as it should be but am continually getting a null pointer error which always links back to
tabHost.setup();
I am using android studio and am new to java. This question has been asked a lot on here but all answers just say to include the setup() and I have already done that.
Here is my .java file:
package com.example.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.TabHost;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec spec1, spec2, spec3;
spec1 = tabHost.newTabSpec("spec1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("Tab1");
tabHost.addTab(spec1);
spec2 = tabHost.newTabSpec("spec2");
spec2.setContent(R.id.tab2);
spec2.setIndicator("Tab2");
tabHost.addTab(spec2);
spec3 = tabHost.newTabSpec("spec3");
spec3.setContent(R.id.tab3);
spec3.setIndicator("Tab3");
tabHost.addTab(spec3);
}
#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);
}
/**
* 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.fragment_main, container, false);
return rootView;
}
}
}
The only difference between my code and some online tutorials is the public class MainActivity extending to ActionBarActivity and not just Activity. I didn't even do this, it was default when i created a blank project.
The XML file is below also:
<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.app.MainActivity$PlaceholderFragment">
<TabHost
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tabHost"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
This Line shows that the TabHost you have created is in fragment_main.xml inside layout directory which is used by PlaceholderFragment
tools:context="com.example.app.MainActivity$PlaceholderFragment"
But you are finding your TabHost in activity_main.xml
Move your code from onCreate() to onCreateView of PlaceholderFragment, below in same class if you are using default template comes with AS like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TabHost tabHost = (TabHost) rootView.findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec spec1, spec2, spec3;
spec1 = tabHost.newTabSpec("spec1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("Tab1");
tabHost.addTab(spec1);
spec2 = tabHost.newTabSpec("spec2");
spec2.setContent(R.id.tab2);
spec2.setIndicator("Tab2");
tabHost.addTab(spec2);
spec3 = tabHost.newTabSpec("spec3");
spec3.setContent(R.id.tab3);
spec3.setIndicator("Tab3");
tabHost.addTab(spec3);
return rootView;
}
Or If you want you can move your TabHost to activity_main.xml as well without changing the java code but that is not recommended using fragments having a lot of benefits.
Check this for benefits of using Fragments
fragment_main and activity_main layouts in Android Studio
This my code to use TabHost,but now I use fragment instead.
public class MainActivity extends TabActivity {
private TabHost tabHost;
private TabHost.TabSpec spec;
#SuppressWarnings("unused")
private Resources res;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main_new);
//Test Button
Button testBtn = (Button)findViewById(R.id.title_imagebtn);
testBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
this.res = getResources();
this.tabHost = getTabHost();
Intent intent = new Intent().setClass(this, LearnResActivity.class);
this.spec = this.tabHost
.newTabSpec(getString(R.string.res_learn))
.setIndicator(
getString(R.string.res_learn),
getResources().getDrawable(
android.R.drawable.ic_media_play))
.setContent(intent);
this.tabHost.addTab(this.spec);
this.tabHost = getTabHost();
intent = new Intent().setClass(this, MyLearnActivity.class);
this.spec = this.tabHost
.newTabSpec(getResources().getString(R.string.my_learn))
.setIndicator(
getString(R.string.my_learn),
getResources().getDrawable(
android.R.drawable.ic_menu_recent_history))
.setContent(intent);
this.tabHost.addTab(this.spec);
this.tabHost = getTabHost();
intent = new Intent().setClass(this, MyTestActivity.class);
this.spec = this.tabHost
.newTabSpec(getString(R.string.my_test))
.setIndicator(
getString(R.string.my_test),
getResources().getDrawable(
android.R.drawable.ic_menu_edit))
.setContent(intent);
this.tabHost.addTab(this.spec);
}}