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);
}}
Related
I am new with Android development, so this is probably a rookie mistake but, I am stuck.
I want to start an activity when clicking on the menu, but the following exception shows up:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.mygymroutine.mygymroutine/com.mygymroutine.mygymroutine.activities.ActivitySchedule}:
java.lang.IllegalArgumentException: No view found for id 0x7f0d008b
(com.mygymroutine.mygymroutine:id/fragment_schedule) for fragment
ScheduleFragment{39f1839 #0 id=0x7f0d008b ...
This is the code related:
public class basic extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
displaySelectedScreen(R.id.nav_schedule);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.basic, 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);
}
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
Intent intent=null;
switch (itemId) {
case R.id.nav_schedule:
intent=new Intent(this, ActivitySchedule.class);
startActivity(intent);
break;
}
Activity code
package com.mygymroutine.mygymroutine.activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.mygymroutine.mygymroutine.Fragments.ScheduleFragment;
import com.mygymroutine.mygymroutine.R;
public class ActivitySchedule extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acivity_schedule);
if(savedInstanceState==null){
ScheduleFragment fg = new ScheduleFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_schedule, fg)
.commit();
}
}
}
Fragment
package com.mygymroutine.mygymroutine.Fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mygymroutine.mygymroutine.R;
public class ScheduleFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
View rootView=inflater.inflate(R.layout.fragment_schedule, container, false);
FloatingActionButton fab=(FloatingActionButton)rootView.findViewById(R.id.fab_schedule);
return inflater.inflate(R.layout.fragment_schedule, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Schedule");
}
}
Fragment Schedule 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"
android:id="#+id/fragment_schedule"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Schedule"
android:textAppearance="?android:attr/textAppearanceLarge" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_schedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="41dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
android:clickable="true"
android:tint="#android:color/background_light"
app:backgroundTint="#android:color/holo_red_light"
app:fabSize="mini"
app:rippleColor="#android:color/transparent"
app:srcCompat="#android:drawable/ic_menu_add" />
</RelativeLayout>
Activity schedule xml:
<?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="com.mygymroutine.mygymroutine.activities.ActivitySchedule">
</android.support.constraint.ConstraintLayout>
Here:
getSupportFragmentManager().beginTransaction().add(R.id.fragment_schedule, fg)
.commit();
You are passing R.id.fragment_schedule as the container of the fragment. Where the fragment will be inserted. However, R.id.fragment_schedule is part of your Fragment. So, it was not inflated yet. You can't use it as container since it was not created yet.
I think you want is:
<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="com.mygymroutine.mygymroutine.activities.ActivitySchedule"
<!-- ADD LINE BELOW -->
android:id="#+id/fragment_container" >
</android.support.constraint.ConstraintLayout>
And change this:
getSupportFragmentManager().beginTransaction().add(R.id.fragment_schedule, fg)
.commit();
to this:
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fg)
.commit();
In. The onOptionsItemSelected method add the following
(This method brings a parameter - MenuItem item)
switch (item.getItemId())
case R.id.myFirst
startActivity(new Intent(this, MyFirstActivity.class));
case R.id.mySecond
startActivity (newIntent(this, MySecondActivity.class));
And so on. You may define a layout for the activity with necessary views. You may also declare the activity in the Manifest file.
This works. I am starting my activities from the main like this.
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'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>
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.
I have built an application in android using Tab Layout and it has 2 tabs. I want a different button on each of these tabs. But if I define button in main.xml, I get same button on both the tabs.
I even tried defining the buttons separately in the class of each tab, but was getting some weird errors. can somebody please help me out with this. Below is my code:
FinalProj.java:
package FinalProj.com;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;
public class FinalProj extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
intent = new Intent().setClass(this, iFallApp.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists",
res.getDrawable(R.drawable.icon))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, Settings.class);
spec = tabHost.newTabSpec("albums").setIndicator("Albums",
res.getDrawable(R.drawable.icon))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(2);
}
}
For Tab1 - iFallApp.java
package FinalProj.com;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class iFallApp extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText("This is the iFall tab");
setContentView(textview);
}
}
Tab 2 - Settings.java
package FinalProj.com;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Settings extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText("This is the Settings tab");
setContentView(textview);
}
}
Main.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">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</LinearLayout>
</TabHost>
I want to have one button along with TextView in iFallApp.java and one button and editText in Settings.java.
For anyone else finding this question:
public class FinalProj extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
The setContentView(R.layout.main) tells the activity what to display on its UI. In this case the view is being set to load from R.layout.main which corresponds to /layout/main.xml (R being the generated lookup class generated by the android framework).
Changing the main.xml would change both tabs because both tabs are contained /within/ the FinalProj activity inside the TabHost view defined inside of main.xml here:
<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">
The whole tab system is described in full detail here:
Tab Layout | Android Developers