I am pretty new to Android. I am making a new App which makes use of Tabs.
Now, I want to display different fragments in the tabs.
Please note that my MinSDK is Android KitKat 4.4 so I wont be using deprecated methods
My Code is:
MainActivity.java
public class MainActivity extends ActionBarActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#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;
}
if(id == R.id.search)
{
Toast.makeText(getApplicationContext(),"You tapped on SEARCH !", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_1, container, false);
Button b1 = (Button) rootView.findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Done", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
}
Fragment_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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$PlaceholderFragment">
<EditText
android:id="#+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter your Name (Fragment Main"/>
<EditText
android:id="#+id/et2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et1"
android:hint="Enter your ID (Fragment Main)"/>
<Button
android:id="#+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="#+id/et2"/>
</RelativeLayout>
Fragment_1.xml
<?xml version="1.0" encoding="utf-8"?>
<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$FragmentOne">
<Button
android:id="#+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="#+id/et2"/>
</RelativeLayout>
I have changed the tools:context in fragment_1.xml for my tests. I don't know what it does
Now, when the user opens the App, he should see the Fragment_Main fragment. When he swipes for the next tab, he should see fragment_1.
Please help in detail as i am very new.
So what exactly doesn't work?
I can only guess, but you don't use Fragment_Main.xml anywhere.
You are already passing position of view pager to your fragment, you should retrieve it and inflate layout based on it. Something like this inside your fragment:
private int mFragmentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mFragmentIndex = getArguments().getInt(ARG_SECTION_NUMBER);
}
}
and in onCreateView you should inflate different layout based on fragment index:
View rootView;
if (mFragmentIndex == 1) {
rootView = inflater.inflate(R.layout.Fragment_Main, container, false);
} else {
rootView = inflater.inflate(R.layout.fragment_1, container, false);
}
Anyway, I would suggest using different fragments, instead of inflating different layouts. Something like this:
#Override
public Fragment getItem(int position) {
if (position == 0) {
return MainFragment.newInstance();
} else {
return SomeOtherFragment.newInstance();
}
}
Related
I'm busy creating an application that uses fragments and tabs. However I was the tabs to do different things depending on which fragment is called.
Here is my main method, What I'm trying to accomplish here is instantiating the activity_main.xml which is listed below and in that xml I'll load a fragment in, this way I can alter the way the tabs work depending on which fragment is called.
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomBar bottomBar = (BottomBar) findViewById(R.id.bottom_bar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//Fragment manager deals with switching fragments within the viewpager
final FragmentManager FM = getSupportFragmentManager();
final FavoriteFragment FF = new FavoriteFragment();
final PlaceholderFragment HF = new PlaceholderFragment();
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
if (tabId == R.id.tab_home)
{
Intent intent = new Intent(getApplicationContext(),HomeFragment.class);
startActivity(intent);
}
else
if (tabId == R.id.tab_favorites)
{
FM.beginTransaction().replace(R.id.fragContainer,FF).commit();
}
else if (tabId == R.id.tab_booked)
{
}
if (tabId == R.id.tab_inbox)
{
Intent intent = new Intent(getApplicationContext(),InboxActivity.class);
startActivity(intent);
}
else if (tabId == R.id.tab_profile)
{
Intent intent = new Intent(getApplicationContext(),ProfileActivity.class);
startActivity(intent);
}
}
});
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SEE";
case 1:
return "DO";
case 2:
return "STAY";
case 3:
return "ENJOY";
}
return null;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.iconiccode.where.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="105dp"
android:id="#+id/fragContainer">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
<!--Bottom Bar-->
<com.roughike.bottombar.BottomBar
android:id="#+id/bottom_bar"
android:layout_gravity="bottom"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
app:bb_tabXmlResource="#xml/bottombar_tabs" />
</android.support.design.widget.CoordinatorLayout>
Homefragment, This is the first fragment behind called.
public class HomeFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private ViewPager mViewPager;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
int tabNumber = getArguments().getInt(ARG_SECTION_NUMBER);
String tabHeader = "";
switch (tabNumber)
{
case 1:
tabHeader="Top Attractions to See";
break;
case 2:
tabHeader="Do This";
break;
case 3:
tabHeader="Stay Here";
break;
case 4:
tabHeader="Enjoy This";
break;
}
textView.setText(tabHeader);
RecyclerView bookedRecycler =(RecyclerView)rootView.findViewById(R.id.bookedRecycler);
RecyclerView vendorRecycler =(RecyclerView)rootView.findViewById(R.id.vendorRecycler);
RecyclerView.LayoutManager vendorLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,false);
RecyclerView.LayoutManager bookedLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,false);
vendorRecycler.setLayoutManager(vendorLM);
bookedRecycler.setLayoutManager(bookedLM);
VendorAdapter venAdapter = new VendorAdapter();
vendorRecycler.setAdapter(venAdapter);
BookedAdapter bookAdapter = new BookedAdapter();
bookedRecycler.setAdapter(bookAdapter);
return rootView;
}
Doing this this way gives me an
"Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.iconiccode.where/com.iconiccode.where.fragments.HomeFragment}; have you declared this activity in your AndroidManifest.xml?"
I have read that there is no need to declare fragments but even after declaring them I still have the same issues. I'm not entirely sure I'm even going about this the correct way
You are populating the fragment in a wrong way
Intent intent = new Intent(getApplicationContext(),HomeFragment.class);
startActivity(intent);
This is the way to initialize activity not the fragment you can look at this tutorial , provided link will explain the process you need to follow for populating a fragment in your activity
This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 6 years ago.
(I already posted a question about this problem that got deleted. I am sorry if I didn't explained my problem good enough. Also I am a german person so forgive me if my english isn't very good.)
I really tried a lot of things to get this simple program to work. I think that the solution to this will be very simple but first you need to find it...
I tried three different ways to code this and ended up with this one based on this Tutorial:
Define the Variable
String[] list = {"One", "Two", "Three"};
Creating the Adapter
ListAdapter Adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
Cast the ListView into the View
ListView mainList1 = (ListView) findViewById(R.id.mainList1);
Set the Adapter (wish causes the problem)
mainList1.setAdapter(Adapter1);
So everytime I am trying to set the Adapter the Program throws out a java.lang.NullPointerException. As I already said I tried a lot of things to get this program to work. This is why I now need the help of the StackOverflow-Comunity. I am trying to explain this problem as good as I can so maybe one day I can finish my project...
These information's might also be relevant to this:
Full MainActivity.java (Original):
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
String[] Vertretung1 = {
"1. Stunde | Frie [Ku] --› Eshk [Et Raum 008]",
"2. Stunde | Frie [Ku] --› Eshk [Et Raum 008]",
"3. Stunde | Frie [Ku] --› Eshk [Et Raum 008]"
};
String[] Vertretung2 = {
"1. Stunde | Grok [Ma] --› Grot [De Raum 111]",
"2. Stunde | Grok [Ma] --› Grot [De Raum 111]",
"3. Stunde | Grok [Ma] --› Grot [De Raum 111]"
};
ListAdapter Adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Vertretung1);
ListView mainList1 = (ListView) findViewById(R.id.mainList1);
mainList1.setAdapter(Adapter1); //Causes the Problem
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
}
public static class FragmentOne extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_one, container, false);
return rootView;
}
}
public static class FragmentTwo extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_two, container, false);
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "HEUTE";
case 1:
return "MORGEN";
}
return null;
}
}
}
Full activity_main.xml (Original):
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="me.muehl.cvovertretungsplan.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Full `fragment_main_one.xml` *(Original)*: [link][2]
Thanks for reading ;)
You must move all ListView things into the Fragment class instead of the activity since that is where you've defined the ListView in the XML.
ListView mainList1 = (ListView) findViewById(R.id.mainList1);
That line will search only in the layout you've used in setContentView.
In order to move the ListView in the Fragment, you can find this line
View view = inflater.inflate...
And get the ListView with the next lines containing...
ListView lv = view.findViewById(...);
// TODO: setAdapter
return view;
I have a MainActivity which is a ActionBarActivity with viewPager inside.
Then I have 3 pages.
In the first page there is a tableLayout with tableRow clickListener (inside blocks) from where I would like to start an intent to another layout without hiding TabBar. Here is my code:
MainActivity.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a FirstFragment (defined as a static inner class below).
//return FirstFragment.newInstance(position + 1);
switch(position) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class FirstFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
//private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.first_fragment, container, false);
createTable(rootView);
return rootView;
}
public static FirstFragment newInstance(String string) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString("msg", "PROVA 1");
fragment.setArguments(args);
return fragment;
}
void createTable(View rootView){
TableLayout ll = (TableLayout) rootView
.findViewById(R.id.tableLayout);
String categorie[];
// MyDatabase db=new MyDatabase(getActivity().getApplicationContext());
// db.open(); //apriamo il db
MyDatabase db = new MyDatabase(getActivity().getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
db.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Cursor c=db.fetchCategorie(); // query
//startManagingCursor(c);
//qui vediamo invece come reperire i dati e usarli, in questo caso li stampiamo in una textview
int categoriaColumn=c.getColumnIndex(MyDatabase.CategorieMetaData.PRODUCT_CATEGORIA_KEY); //indici delle colonne
//int priceCol=c.getColumnIndex(MyDatabase.ProductsMetaData.PRODUCT_PRICE_KEY);
ArrayList<String> categorieList = new ArrayList<String>();
if(c.moveToFirst()){ //se va alla prima entry, il cursore non è vuoto
do {
categorieList.add(c.getString(categoriaColumn)); //add to arraylist
//productsTv.append("Product Name:"+c.getString(nameCol)+", Price:"+c.getInt(priceCol)+"\n"); //estrazione dei dati dalla entry del cursor
//Log.d("Prova", "PROVA:"+ "Product Name:"+c.getString(categoriaColumn)+", Price:"+c.getInt(priceCol)+"\n");
} while (c.moveToNext());//iteriamo al prossimo elemento
}
db.close();
categorie = categorieList.toArray(new String[categorieList.size()]);
for (int i = 0; i < categorie.length; i++) {
TableRow tbRow = new TableRow(getActivity().getApplicationContext());
tbRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView tv1 = new TextView(getActivity().getApplicationContext());
tv1.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
tbRow.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
ImageView imageView = new ImageView(getActivity().getApplicationContext());
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher));
tv1.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv1.setId(i);
tv1.setText(categorie[i]);
tv1.setTextColor(Color.parseColor("#000000"));
tbRow.addView(imageView);
tbRow.addView(tv1);
ll.addView(tbRow, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
final String finalCategorie[] = categorie;
final int finalI = i;
final View finalRootView = rootView;
tbRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Intent newIntent = new Intent(MainActivity.this, detailActivity.class);
// newIntent.putExtra("key", strings[finalI]);
Log.d("TEST", "Row selected: " + finalCategorie[finalI]);
// startActivity(newIntent);
// Intent intent = new Intent(getActivity(), EventiFragment.class);
// startActivity(intent);
}
});
}
}
}
public static class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentSecond);
tv.setText(getArguments().getString("msg"));
return v;
}
public static SecondFragment newInstance(String string) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 2");
f.setArguments(b);
return f;
}
}
public static class ThirdFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.third_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentThird);
tv.setText(getArguments().getString("msg"));
return v;
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 3");
f.setArguments(b);
return f;
}
}
public static class EventiFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.eventi_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentEventi);
tv.setText(getArguments().getString("msg"));
return v;
}
public static EventiFragment newInstance(String string) {
EventiFragment f = new EventiFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 2");
f.setArguments(b);
return f;
}
}
}
first_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayout1"
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.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:contentDescription="#string/main_photo_description"
android:scaleType="centerCrop"
android:src="#drawable/main_photo" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TableLayout>
</LinearLayout>
</ScrollView>
eventi_fragment.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="com.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/FragmentEventi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView"
android:textSize="26sp"/>
So I would create a separate layout, but instead of putting the layout in two separate XML files, put it all in one. For example
<?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:orientation="vertical" >
<RelativeLayout
android:id="#+id/intent_replacement"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Here's the stuff for the supposed intent -->
</RelativeLayout>
</RelativeLayout>
So in this you can have one attribute called visible then programmatically you just get the Layout as an object and when an item in the table is clicked on use intentLayoutObject.setVisibility(true)
Likewise when you get back button pressed intentLayoutObject.setVisibility(false)
I've looked at several similar questions on here, but none of them have explained my problem. I am simply trying to reference a TextView by it's id, but I keep getting Null Pointer Exceptions whenever I try to do anything with it. I made sure to put my assignment after both setContentView() is called and the fragment is inflated. To make sure there wasn't anything else causing problem I removed the other portions of my code and tested for null immediately after assignment. Regardless of this, it's still showing as null.
Here's my code:
public class MainActivity extends Activity
{
//MEMBER VARIABLES
TextView mQuestionText;
#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();
}
mQuestionText = (TextView) findViewById(R.id.questionTextView);
if (mQuestionText == null)
System.out.println("debug:: " + "null");
}
#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;
}
}
}
And here's the fragment_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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="edu.wichita.eecs.cs697ac.w387u669.assignment3.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/questionTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:text="Question"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/questionTextView"
android:text="False" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/questionTextView"
android:layout_marginTop="35dp"
android:layout_toLeftOf="#+id/questionTextView"
android:text="True" />
</RelativeLayout>
Thanks for your help!
EDIT: After doing some other research, I learned that I could override the onStart() method and move my code there as I would have access to the views (even those from the fragment). However this is just a bypass that doesn't really use fragments as they are meant to be used.
protected void onStart()
{
super.onStart();
TextView test = (TextView) findViewById(R.id.questionTextView);
test.setText("hello");
}
Hope that helps someone
questionTextView TextView is in fragment_main.xml layout of PlaceholderFragment, so use onCreateView of Fragment to initialize TextView as:
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView mQuestionText = (TextView)rootView.findViewById(R.id.questionTextView);
if your using Fragment you shoud reference it from the fragment OnCreateView method
public class MainActivity extends Activity {
#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);
TextView QuestionText = (TextView) rootView.findViewById(R.id.questionTextView);
if (mQuestionText == null)
System.out.println("debug:: " + "null");
return rootView;
}
} }
You have set setContentView(R.layout.activity_main) but your xml name is fragment_main.xml
Use this XML in setContentView i.e. setContentView(R.layout.fragment_main)
This is my first experience with android. I'm trying to add items to my ListView.
I use Tabs, and the only way to see that the item was added is to change tab and then come back to the first tab.
I searched around, and I've always found
adapter.notifyDataSetChanged();
but doesn't work for me.
I have created the project with, as I said, Fixed Tabs + Swipe.
I simply want to have listviews which rows have an EditText, a Spinner and a Button.
On the bottom of the Fragment used for the tab, I have an ImageButton. I want to click on it and have a new Row.
my custom Adapter:
package com.andreapivetta.uconverter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final int resourceID;
public CustomAdapter(Context context, int resource, ArrayList<String> bah) {
super(context, resource, bah);
this.context = context;
this.resourceID = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(resourceID, parent, false);
return rowView;
}
}
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" >
<ListView
android:id="#+id/unitListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<ImageButton
android:id="#+id/moreImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/image_button_delete"
android:src="#android:drawable/ic_input_add" />
</RelativeLayout>
Row.xml
<?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">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<EditText
android:id="#+id/unitEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/unitSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageButton1"
android:layout_marginBottom="15dp"
android:layout_toRightOf="#+id/unitEditText" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/unitEditText"
android:layout_alignParentRight="true"
android:onClick="removeItem"
android:contentDescription="#string/image_button_delete"
android:src="#android:drawable/ic_menu_delete" />
</RelativeLayout>
MainActivity...
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* 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.
*/
ArrayList<String> myStringArray1 = new ArrayList<String>();//new String[]{"Egzo","Eg","Egzona"};
String[] myStringArray2 = new String[]{"aaa","bbb","ccc"};
String[] myStringArray3 = new String[]{"ddd","eeee"};
String[] myStringArray4 = new String[]{"Cia","ci","Ciao"};
public static ArrayAdapter<String> adapter;
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)));
// ListView
ListView unitListView = (ListView) rootView.findViewById(R.id.unitListView);
switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
myStringArray1.add("mmm");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
unitListView.setAdapter(adapter);
break;
case 2:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray2);
unitListView.setAdapter(adapter);
break;
case 3:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray3);
unitListView.setAdapter(adapter);
break;
case 4:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray4);
unitListView.setAdapter(adapter);
break;
}
unitListView.setOnItemClickListener(listViewOnClickListener);
// ImageButton
ImageButton moreImageButton = (ImageButton) rootView.findViewById(R.id.moreImageButton);
moreImageButton.setOnClickListener(moreListener);
return rootView;
}
public OnClickListener moreListener = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myStringArray1.add("Andrea");
adapter.clear();
adapter.addAll(myStringArray1);
adapter.notifyDataSetChanged();
}
};
public OnItemClickListener listViewOnClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
};
}
}
Note that I'm working only with the first tab right now...
What am I doing wrong? :)
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
#Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
public OnClickListener moreListener = new OnClickListener() {
#Override
public void onClick(View v) {
adapter.add("aaaa")
}
}