Can't make my Listview appear [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm working on an android application and cannot seem to make my listView appear when the app is run. I've been toggling with some of the xml but I'm still rather new and android updates quite often so tutorials are constantly becoming outdated.The actual java code seems fine to me I can't see much difference there. I could really use an extra pair of eyes on this , maybe there is something I'm missing.
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
}
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] forecastArray = {
"Today, colder than bumblefuck",
"Friday, condsider moving",
"Saturday, not even gonna bother",
"Sunday, Partly Cloudy",
"Monday, Hell Froze over",
"Tuesday, Cloudy with a chance of meatballs",
"Wednesday,Light Showers"
};
List<String> weekForeCast = new ArrayList<String>(
Arrays.asList(forecastArray));
ArrayAdapter<String> bindIt= new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForeCast);
ListView listView = (ListView) inflater.inflate(R.layout.fragment_main, container, false).findViewById(R.id.listview_forecast);
listView.setAdapter(bindIt);
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
<FrameLayout 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=".MainActivityFragment">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listview_forecast">
</ListView>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:id ="#+id/list_item_forecast_textview"
android:visibility="visible"
android:enabled="false">
</TextView>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/fragment"
android:name="com.alesterlewis.sunshine.app.MainActivityFragment"
tools:layout="#layout/fragment_main" android:layout_width="match_parent"
android:layout_height="match_parent" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alesterlewis.sunshine.app" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>

The problem is that you are inflating a new view while returning from the onCreateView. Thus, the one in which you had set the adapter and for the listview is lost. This is the bug.
First inflate the layout for the fragment in the view
View view = inflater.inflate(R.layout.fragment_main, container, false);
Then initialise its components, here you can set the list view adapter, etc and if you would have had more view, initialised the same.
ArrayAdapter<String> bindIt= new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForeCast);
ListView listView = (ListView) view.findViewById(R.id.listview_forecast);
listView.setAdapter(bindIt);
and in the end return the same view that was initially infalated and worked upon!

Did you set an adapter for your list? Maybe your adapter list is empty for some reason.
UPDATE
Try to anticipate the view creation:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {
"Today, colder than bumblefuck",
"Friday, condsider moving",
"Saturday, not even gonna bother",
"Sunday, Partly Cloudy",
"Monday, Hell Froze over",
"Tuesday, Cloudy with a chance of meatballs",
"Wednesday,Light Showers"
};
List<String> weekForeCast = new ArrayList<String>(
Arrays.asList(forecastArray));
ArrayAdapter<String> bindIt= new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForeCast);
ListView listView = (ListView) view.findViewById(R.id.listview_forecast);
listView.setAdapter(bindIt);
return view;
}

Related

What is fragment?How to add a frgament to an existing activity?And how to modify layout of a fragment

I am new to android,and i want to create a fragment which has listview in it and i want to add that fragment to my main activity.I am trying but i cant add it to my activity and also cant define my own layout to it.So please help me.
Thanks in advance.
This is my MainActivity.java
package com.example.sample;
import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
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.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
String[] codeLearnChapters = new String[] { "Android Introduction","Android Setup/Installation","Android Hello World","Android Layouts/Viewgroups","Android Activity & Lifecycle","Intents in Android"};
ArrayAdapter<String> codeLearnArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, codeLearnChapters);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView codeLearnLessons = (ListView) findViewById(R.id.idListView1);
setContentView(R.layout.activity_main);
codeLearnLessons.setAdapter(codeLearnArrayAdapter);
}
#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);
}
}
And its xml is
<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=".MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="300dp"
android:name="com.example.sample.myFragment"
android:id="#+id/fragment"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
My fragment java is myFragment.java
package com.example.sample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created on 11/4/2015.
*/
public class myFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.act_fragment,
container, false);
return view;
}
}
Its xml i.e act_fragment.xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/idListView1">
</ListView>
</RelativeLayout>
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
In my words, a fragment is a sub-activity.
You can read more about what a fragment is http://developer.android.com/guide/components/fragments.html
There is also a sample which you could use (and will be helpful as you will learn something new). The sample is http://developer.android.com/training/basics/fragments/index.html
You can also look it up on youtube (once you have read about it and understood what fragment is). There is also a video tutorial to start you with. Just search "Android Fragment Lifecycle Part 1: Android Application Development Tutorial [HD 1080p]" - sorry, Stackoverflow is not allowing me to add more than two links.
They have five tutorials and I would recommend it as it will help you start better by yourself.
You can read more about what a fragment is
link
Code :
public class Tab2Fragment extends Fragment {
EditText fromdate;
EditText todate;
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.tab2_view, container, false);
EditText fromdate=(EditText)V.findViewById(R.id.fromdate);
EditText todate=(EditText)V.findViewById(R.id.todate);
fromdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// Listview Data
String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
"iPhone 4S", "Samsung Galaxy Note 800",
"Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
lv = (ListView) V.findViewById(R.id.list_view);
// Adding items to listview
adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
return V;
}
}
hope this link helpful you
http://developer.android.com/guide/components/fragments.html
Place this in your activity class
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
and place below code in activitylayout code
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MergeRootFrame" />

Android Listview Hides Titlebar

I'm trying to make an app - it has 3 activities. The first 2 are listviews in linear layouts, and each of them prevents the title bar from showing up. By title bar I mean the section that is normally at the top of an activity which displays the activity's name as well as an option setting. My third activity is not a listview, and displays the title bar normally, which leads me to think it may be a problem with my listviews.
The xml for my first page is:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".SelectClass">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
My java class doesn't do much to the display, although it does set an array adapter and an onClick listener. If those are necessary to understand what's going on then let me know and I'll post them. I appreciate any help or clues. Thank you!
EDIT: first page's java:
package com.example.graeme.dnd5echaracterroller;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.view.View;
import android.widget.TextView;
public class SelectClass extends ListActivity {
private static String classString;
public static void setClassString(String classString) {
SelectClass.classString = classString;
}
public static String getClassString() {
return classString;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_class);
//Initialize the available class choices
final String[] classes = {"Barbarian","Bard","Cleric","Druid",
"Fighter","Monk","Paladin","Ranger","Rogue","Sorcerer",
"Warlock", "Wizard"};
ArrayAdapter<String> classAdapter = new ArrayAdapter<>(getListView().getContext(),
R.layout.classlayout, R.id.classname, classes);
getListView().setAdapter(classAdapter);
//Set on click listener to get selected class item
AdapterView.OnItemClickListener itemClickedHandler = new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Start a new intent headed to selectRoll, fill it with the class string selected
Intent sendClassIntent = new Intent(SelectClass.this, SelectRoll.class);
//Each list item has an image, and text
//First grab the list item, then grab the text from it
LinearLayout ll = (LinearLayout)v;
TextView tv = (TextView)(ll).findViewById(R.id.classname);
setClassString((String)(tv.getText()));
startActivity(sendClassIntent);
}
};
getListView().setOnItemClickListener(itemClickedHandler);
}
#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_select_class, 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);
}
}
You should modify you first activity as this structure
public class SelectClass extends AppCompatActivity {
...
private ListView mListView;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_class);
// Initialize the lisview
mListView = (ListView) findViewById(R.id.lisview_id); // lisview id
//Initialize the available class choices
final String[] classes = {"Barbarian","Bard","Cleric","Druid",
"Fighter","Monk","Paladin","Ranger","Rogue","Sorcerer",
"Warlock", "Wizard"};
ArrayAdapter<String> classAdapter = new ArrayAdapter<> (this,
R.layout.classlayout, R.id.classname, classes); // update
mListView.setAdapter(classAdapter);
...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
....
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
.....
}
}
And in the ListView of first activity
<ListView
android:id="#+id/lisview_id" // use this id for initialize listview
android:layout_width="match_parent"
android:layout_height="match_parent">
Hope this help
I think that the problem is not the ListView, normally it is hided because of the style you have set in your manifest. This is what you have in the main activity inside manifest.xml:
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
the android:theme="#style/AppTheme" on the listView activity must be set as the Apptheme that shows the "Title bar".
Hope this helps

<Activity name> cannot be resolved or not a field

I'm trying to perform a simple navigation action using Intent.
I'm using the complete ADT bundle which includes eclipse, SDK and ADT plugins, so no need to configure ADT separately in eclipse.
1.) I started by creating two layouts named activity_main.xml and test2.xml.
2.) Corresponding java files are mainActivity.java and test2.java.
3.) Now activity_main.xml contains a button with id = "click" . Clicking this button should navigate to next activity i.e test2.xml.
4.) The code in mainActivity.java is as below
package com.example.test;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
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.Button;
import android.os.Build;
public class MainActivity extends ActionBarActivity
{
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
btn = (Button)findViewById(R.id.click);
//Listening to button event
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), test2.class);
startActivity(nextScreen);
}
});
}
#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;
}
}
}
5.) But when i did so the findViewById(R.id.click) showed error saying "click cannot be resolved or is not a field"
6.) Eclipse suggested me to create a field click in id which i did. It modified the R.java file but it did not help. Though the errors were gone but the emulator threw error saying "the application has stopped"
7.) My manifest.xml file is as below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.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>
<activity
android:name=".test2"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.test.test2" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
8.) Now my test2.java code is
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import com.example.test.R;
public class test2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
TextView txtName = (TextView) findViewById(R.id.textView1);
txtName.setText("This is test2 activity");
}
}
Even here at setContentView(R.layout.test2) it shows the similar error as "test2 cannot be resolved or not a field" where as setContentView(R.layout.activity_main) did not show this error
9.) My fragment_main.xml code is as below
<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: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.test.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerInParent="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="65dp"
android:text="#string/button" />
</RelativeLayout>
10.) My test2.xml code is as below
<?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="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="second page"
android:layout_gravity="center"
/>
</LinearLayout>
The error displayed on running the application is as below
a.) [2014-04-15 18:39:03 - test] W/ResourceType( 8160): ResXMLTree_node header size 0 is too small.
b.) [2014-04-15 18:39:03 - test] C:\Users\KC\Desktop\Android-budle\test\res\menu\main.xml:6: error: Error: No resource found that matches the given name (at 'title' with value '#string/action_settings').
I'm not able to understand what am I missing. Please provide me a solution for this issue, Thanks in advance.
Firstly Check your layout xml. I there is any error then correct it.After that press alt+p then select clean after that it will be build again.
In your activity_main.xml>Button you need to put the android:onClick="methodName". The in your main_activity you schould implement methodName. There you can handle the activities once the Button is clicked.
Another way is to implement the onClickListener to sepertate the XML and the Java files.
Can you add your layout XML files?
Write the onClickListener for your button in your MainActivity onCreate() method and inside it redirect to test2 activity as below:
btn = (Button)findViewById(R.id.click);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,test2.class);
startActivity(intent);
}
});
EDITED:
You need to set your view as fragment_main.xml besides activity_main as your Button is inside fragment_main layout.
Just change the
setContentView(R.layout.activity_main);
to
setContentView(R.layout.fragment_main);
There is something wrong syntax wise with your xml files (test2 or activity_main) due to which the auto generated R file will no longer generate the id for the button view.
The main problem seems to be with activity_main as the button contained in it is no longer converted to its corresponding value in R file.
Check those files and if not able to figure out than put the code in order to get help.
Last but not the least check if you have the import statement like import android.R.
You don't need this to be there as it causes such errors if present.
UPDATE:
You are using -
1) setContentView(R.layout.activity_main);
2) btn = (Button)findViewById(R.id.click);
But your layout where you defined your button is setContentView(R.layout.fragment_main);
So btn is trying to find the view in activity_main which is not available.
Solution -
Set the content view to setContentView(R.layout.fragment_main).

Add an XML files content inside another XML document dynamically in Android using Eclipse

I'm very new to Android Development and I'd like to add a page to another dynamically. I'm a C# web developer and would like to do the same as using a Master Page and inserting other pages in this page.
The code I have at the moment is as follow: (Keep in mind that I've never done this, and any and all advise would be appreciated.)
I Have 3 main documents I'm working on at the moment:
Pharma Manifest.xml
MainActivity.java
fragment_main_dummy.xml(I'm using the dummy since it's already doing what I want.)
Here is the content on MainActivity.xml
package com.pharma.pharma;
import org.w3c.dom.Text;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.location.Address;
import android.os.Bundle;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
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.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(getActionBarThemedContextCompat(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
getString(R.string.title_Dashboard),
getString(R.string.title_Customers),
getString(R.string.title_Products),
getString(R.string.title_Detailing),
getString(R.string.title_Appointments),
getString(R.string.title_Events), }), this);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if
* <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#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 onNavigationItemSelected(int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
return true;
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
dummyTextView.setText("blah Blah Dashboard");
break;
case 2:
dummyTextView.setText("blah Blah Customers");
break;
case 3:
dummyTextView.setText("blah Blah Products");
break;
case 4:
dummyTextView.setText("blah Blah Detailing");
break;
case 5:
dummyTextView.setText("blah Blah Appointments");
break;
case 6:
//Insert XML to fragment dummy here as a test
break;
default:
//throw error
}
return rootView;
}
}
}
Here is the code in the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pharma.pharma"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.pharma.pharma.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>
And lastly the code for fragment_main_dummy.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: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=".MainActivity$DummySectionFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true" />
<include
android:id="#+id/section_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
layout="#layout/dashboard" />
</RelativeLayout>
I've sat with this for days.
I'm still new at this and can't figure it out. I'm also pressured to get this whole project done in about a months time. Any help would be greatly appreciated.
Your title is conceptually wrong, you don't one XML to another. Those XML are heavily crunched and pre-compiled during the compile time and don't exist as you see them in the final app.
Further, those XML are just representations for the system to build Views and inside ViewGroups which is a class that extends View you can call .addView(view);
The include xml code you use, is a good way to re-use static generated XML, but for dynamic generated stuff you need to do it via code.
I've notice you're using fragments stuff. So probably you're better use the Fragment route of dynamically adding/removing stuff
The code you created inside onNavigationItemSelected is pretty much everything you need to do to dynamically change stuff around.
The fragment you're creating/instantiating will override onCreateView to inflate a new View and return it. That new view will be inserted on android.R.id.content (that is the View ID for your whole content) or for any ID that you specified in your XML.
hope it helps.
You could use LayoutInflater to do that.
eg.
RelativeLayout relativeLayout= (RelativeLayout) findViewById(R.id.relativeLayout);
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
relativeLayout.addView(childIndex, layoutInflater.inflate(R.layout.newLayoutToAdd, this, false) );

Android: Landscape layouts not being used

In my application I have one Main activity that sets up a tabbed ViewPager with three different fragments, each one with it's own layout and class. I've created landscape versions of each layout file and placed them all in res/layout-land. But when I run the app and switch orientations, the landscape layout isn't being used?
MainActivity:
package me.zaydbille.utilitywatch;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
// Tab and ViewPager variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Coin Flip", "Counter", "Choice"};
int numTabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, numTabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#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) {
Intent myIntent = new Intent(this, HelpActivity.class);
startActivity(myIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
// Counter Fragment helper methods
public void addCount() {
Preferences.setIntPref(this, Preferences.getIntPref(this) + 1);
}
public void clearCount() { Preferences.setIntPref(this, 0); }
public int getCount() { return Preferences.getIntPref(this); }
// Choice Fragment helper methods
public void saveList(ArrayList<String> list){ Preferences.saveList(this, list); }
public ArrayList<String> getList() { return Preferences.getList(this); }
}
Fragment 1:
package me.zaydbille.utilitywatch;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import java.util.Random;
public class CoinFlip extends Fragment {
Button flipButton;
Random randomizer;
ImageView mSpinningCoin;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.coin_flip,container,false);
flipButton = (Button) v.findViewById(R.id.flipButton);
mSpinningCoin = (ImageView) v.findViewById(R.id.coin_spinning);
flipButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
randomizer = new Random();
int number = randomizer.nextInt(2);
if (number == 0) { // Heads
((AnimationDrawable) mSpinningCoin.getBackground()).stop();
mSpinningCoin.setBackgroundResource(R.drawable.coin_spin_heads);
((AnimationDrawable) mSpinningCoin.getBackground()).start();
} else if (number == 1) { // Tails
((AnimationDrawable) mSpinningCoin.getBackground()).stop();
mSpinningCoin.setBackgroundResource(R.drawable.coin_spin_tails);
((AnimationDrawable) mSpinningCoin.getBackground()).start();
}
}
});
return v;
}
}
Fragment 1's layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/ColorPrimaryLight">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:layout_alignParentBottom="false"
android:gravity="center_vertical|center_horizontal"
android:layout_marginTop="200dp">
<ImageView
android:id="#+id/coin_spinning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/coin_spin_heads"
android:contentDescription="#string/coinDescription" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/flipButtonText"
android:id="#+id/flipButton"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.zaydbille.utilitywatch" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenLayout|screenSize"
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=".HelpActivity"
android:label="#string/title_activity_help"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="me.zaydbille.utilitywatch.MainActivity" />
</activity>
</application>
</manifest>
When you use android:configChanges="orientation|screenLayout|screenSize" you are saying that you do not want the system to do any of its default behavior when these configuration changes happen. This includes changing any layouts. Remove that line or actually handle the change yourself.
Just remove this piece of code from your AppManifest.xml:
android:configChanges="orientation|screenLayout|screenSize"
This disables your activity to change its orientation. Removing that will fix it.

Categories

Resources