Android: Landscape layouts not being used - android

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.

Related

Can't make my Listview appear [closed]

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;
}

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

How to Change a size of fragment?

Pretty new to android development, I need to know how I can change the size of my ListView in my fragment pragmatically to cover the entire screen? match_parent, fill_parent didn't work.
I have hard coded values of 500dp
Here is my fragment
<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"
tools:context=".MainActivity">
<ListView
android:id="#android:id/list"
android:layout_width="500dp"
android:layout_height="500dp"
android:divider="#null"
android:dividerHeight="0dp"
android:layout_marginTop="0dp">
</ListView>
</RelativeLayout>
and here is JAVA my fragment code:
import android.app.ListFragment;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import java.util.List;
public class MyFragment extends ListFragment {
List<data> flowers = new datadata().getdatas();
public MyFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataArrayAdapter adapter = new dataArrayAdapter(getActivity(),
R.layout.data_listitem,
flowers);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
return rootView;
}
}
here is my main Activity class
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbarStyle="insideOverlay"
android:scrollbars="none"
android:fadeScrollbars="true"
android:fitsSystemWindows="true"
android:layout_gravity="top"
>
</ScrollView >
and this is my main activity java code:
package mshirvan.example.com.netplex;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.view.View.OnClickListener;
import data.row1;
public class MainActivity extends Activity {
public static float screenx = 0;
public static float screeny = 0;
public static int screenpixelx = 0;
public static int screenpixely = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScreenUtility utility = new ScreenUtility(this);
screenx = utility.getWidth();
screeny = utility.getHeight();
screenpixelx = utility.getPixelWidth();
screenpixely = utility.getPixelHeight();
MyFragment frag = new MyFragment();
getFragmentManager().beginTransaction()
.add(R.id.myContainer, frag)
.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) {
ScreenUtility utility = new ScreenUtility(this);
String output = "Width: " + utility.getWidth() + ", " +
"Height: " + utility.getHeight();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Add the following to your fragment RelativeLayout. This should be as follows:
android:layout_width="match_parent"
android:layout_height="500dp"
For example the map layout fragment should be as follows :
<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="500dp"
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"
>
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
Then add this fragment layout in the main layout.
put these in your listview too:
android:layout_width="match_parent"
android:layout_height="match_parent"
or you can change the layoutparameters to match_parent in yout fragment
that contains the listview.
you have to set the fragment container height to match parent not ListView. in your case ,ListView will fill it's parent height. ListView's parent is RelativeLayout and the RelativeLayout height is matchParent that means , RelativeLayout will also fill it's container and it's container is your fragment place holder that defined in your activity's layout file. you have to set that container's height to matchParent.
I think the problem is that you are trying to add fragment to ScrollView. use FrameLayout with android:layout_height=match_parent for fragment's container and if you have to add multiple fragments, then define multiple FrameLayouts in your activity's layout or add them dynamically.

Navigation Drawer, ListView Items don't show

I'm trying do a news sports app with a NavigationDrawer. But when I open the app I want to show a WebView and after from left to come the ListView. I did something but now the ListView doesn't show the items. I have 4 classes and 2 xml.
package com.baronescu.sportsnews2;
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = new String[]{"Football","Tennis","Basketball","Hockey","Handball"};
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);
dList.setAdapter(adapter);
dList.setSelector(android.R.color.holo_blue_dark);
dList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.dfurl, detail).commit();
}
});
Thread timer = new Thread(){
public void run (){
try {
sleep(2000);
} catch (InterruptedException e ){
e.printStackTrace();
} finally {
Intent odu = new Intent ("com.baronescu.sportsnews2.DEFAULTURL");
startActivity(odu);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
package com.baronescu.sportsnews2;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailFragment extends Fragment {
TextView text;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
View view = inflater.inflate(R.layout.menu_detail_fragment, container, false);
String menu = getArguments().getString("Menu");
text= (TextView) view.findViewById(R.id.detail);
text.setText(menu);
return view;
}
}
package com.baronescu.sportsnews2;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import com.baronescu.sportsnews2.OurViewClient;
public class DefaultUrl extends Activity {
WebView firstnews;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstnews = (WebView) findViewById(R.id.dfurl);
firstnews.setWebViewClient(new OurViewClient());
firstnews.getSettings().setJavaScriptEnabled(true);
firstnews.getSettings().setLoadWithOverviewMode(true);
firstnews.getSettings().setUseWideViewPort(true);
try {
firstnews.loadUrl("http://www.digisport.ro");
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.baronescu.sportsnews2;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class OurViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView v, String url) {
// TODO Auto-generated method stub
v.loadUrl(url);
return true;
}
}
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/sportsnews" >
<!-- android:id="#+id/content_frame" -->
<!-- android:layout_width="match_parent" -->
<!-- android:layout_height="match_parent" > -->
<WebView
android:id="#+id/dfurl"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
<?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:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="40px" />
</LinearLayout>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.baronescu.sportsnews2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/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>
<activity
android:name=".DefaultUrl"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.baronescu.sportsnews2.DEFAULTURL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Start reading that does not hurt!
implementing drawer navigation
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
The main content view (the FrameLayout above) must be the first child in the DrawerLayout because the XML order implies
z-ordering and the drawer must be on top of the content.
The main content view is set to match the parent view's width and height, because it represents the entire UI when the navigation drawer is hidden.
The drawer view (the ListView) must specify its horizontal gravity with the android:layout_gravity attribute. To support right-to-left (RTL) languages, specify the value with "start" instead of "left" (so the drawer appears on the right when the layout is RTL).
The drawer view specifies ts width in dp units and the height matches the parent view. The drawer width should be no more than 320dp so the user can always see a portion of the main content.
As a good practice i recommend:
create layout for drawer as above
create main activity consuming layout
create second layout (main content layout) with WebView
make fragment for coresponding layout
add fragment via transaction in main activity

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) );

Categories

Resources