Android SherlockFragmentActivity call SherlockFragment - android

Originally, I have 2 Activities. A call B activities. Now I changed the A class extends SherlockFragmentActivity and B class extends SherlockFragment.
I tried to changed these in A class:
private class MyTabListener implements ActionBar.TabListener {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getPosition()==1) {
B frag = new B();
ft.replace(android.R.id.content, frag);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
//=============================
In B class:
public class Br extends SherlockFragment{
/* Called when the activity is first created */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.promotionslist_tableview);
//get our listview
ListView myListView = (ListView) findViewById(R.id.myListView_promotionslist_table);
//==============================
BUT ERROR.
1. onCreate
2. findViewById..
What i am wrong ?
please give me some hints. Thanks.

I can now display the B fragement but the listview overlap on the main listview..?
Why ?
public class B extends SherlockFragment{
View view;
/* Called when the activity is first created */
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//setContentView(R.layout.promotionslist_tableview);
//get our listview
ListView myListView = (ListView) view.findViewById(R.id.myListView_promotionslist_table);
.
.
.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.promotionslist_tableview, container, false);
return view;
}

You have to use the onCreateView() method in fragments:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout, null);
return view;
}
There you can inflate a View and call findViewById like this:
view.findViewById(...);

Related

Error while working with two Fragment in android

I am new in android i am stuck while working with fragment any help in this is really appreciated.I am working with fragment for tablet. There are two fragment suppose FragmentA(Left side fragment) and FragmentB(Right side Fragment) both are list fragment, FragmentB change according to FragmentA. There is another fragment, FragmentC which inflates on clicking the item on List of FragmentB. Now after inflating the FragmentC when I click on the FragmentA my app Crashes. There is an error in logcat showing FragmentC can't cast into FragmentB. I am trying to solve this problem from last 10 hours but no result came out.
This is my MainActivity class
public class MainActivity extends FragmentActivity implements FragmentA.Communicator{
FragmentManager manager;
FragmentB frag2;
FragmentA frag1;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frag);
manager=getSupportFragmentManager();
FragmentA frag1=(FragmentA ) manager.findFragmentById(R.id.fragment1);
frag1.setCommunicator(this);
}
#SuppressLint("NewApi")
#Override
public void respond(int index) {
// TODO Auto-generated method stub
frag2= (FragmentB) manager.findFragmentById(R.id.fragment2);
frag2.changeData(index);
}
}
This is my FragmentA class
public class FragmentA extends Fragment implements OnItemClickListener{
Communicator comm;
ListView list;
String[] items={"Beverages","Food"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu_list,container, false);
list=(ListView) view.findViewById(R.id.listView1);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,items);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
// TODO Auto-generated method stub
comm.respond(i);
}
public void setCommunicator(Communicator communicator){
this.comm=communicator;
}
public interface Communicator{
public void respond(int index);
}
}
This is my FragmentB class
public class FragmentB extends Fragment implements OnItemClickListener {
ListView listmenu;
String[] listItem1={"item1","item2","item3","item4","item5"};
String[] listItem2={"itemA","itemB","itemC","itemD","itemE"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu, container, false);
listmenu=(ListView) view.findViewById(R.id.listView_menu);
return view;
}
public void changeData(int index){
if(index==0){
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,listItem1);
listmenu.setAdapter(adapter);
}
}
if(index==1){
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,listItem2);
listmenu.setAdapter(adapter);
}
listmenu.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
//Intent intent = null;
switch(position){
case 0: FragmentManager manager=getFragmentManager();
Fragment frag1=new FragmentC();
FragmentTransaction ft=manager.beginTransaction();
ft.replace(R.id.fragment2, frag1,"A");
ft.addToBackStack("A");
ft.commit();
break;
}
}
}
I think you need check which of the 2 fragments is 'alive'. If Fragment B is active try to close it first and re-open Fragment A. Then you can continue the process.

Change number of buttons in Fragment on Tab click

I have created 10 tabs programmatically and want to change number of buttons that are placed in fragment when a tab is clicked by user.
My 'MainActivity' code:
public class MainActivity extends Activity {
int numberOfButtons=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentA fragmentA = new FragmentA();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.mainLayout,fragmentA,"fragA");
transaction.commit();
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i=0;i<10;i++)
{
ActionBar.Tab tab = actionBar.newTab().setText("Tab"+i).setTabListener(new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
numberOfButtons = 10;
sendNumber(numberOfButtons);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
});
actionBar.addTab(tab);
}
}
This is my fragment code:
public class FragmentA extends Fragment implements View.OnClickListener{
Button btn;
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int numberOfButtons= getArguments().getInt("someInt",0);
LinearLayout view = new LinearLayout(getActivity());
// Inflate the layout for this fragment
view.setOrientation(LinearLayout.VERTICAL);
view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
for (int i = 0;i<numberOfButtons;i++)
{
btn = new Button(getActivity());
view.addView(new Button(getActivity()));
}
myView = view;
return myView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v) {
}
}
I am calling the numbeOfButtons method inside the MainActivity and want to send number of buttons to Fragment when a tab is clicked. However the application throws error after line fA.numberOfBtns(numberOfButtons); is called. The error is reflect.InvocationTargetException.
How can I change the number of buttons in Fragment when a tab is clicked?
You may want to use newInstance technique to pass parameters during Fragment initialization. Here is a small example taken from here:
public static MyFragment newInstance(int someInt) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("someInt", someInt);
myFragment.setArguments(args);
return myFragment;
}
And later you can access this parameter:
getArguments().getInt("someInt", 0);

Action bar tabs

im trying to use action bar tabs and i have some questions.
I see from the developers blog that i need to use Fragment layout. I have in my wanted layout buttons that the margins between them is depends on the screen size.
I used to do in Relative layout but in Fragment layout it doest work.
Is there a way to change the view position from the java code?
My views dont respone to setOnClickListener anymore.
I tried using this code:
View homePageLayout = View.inflate(this, R.layout.home_page, null);
workoutWall = (ImageButton) homePageLayout.findViewById(R.id.workoutWall);
workoutWall.setOnClickListener(this);
And my fragemnts code:
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(tab.getPosition() == 0)
{
ft.add(R.id.fragment_place, fragmentHome, null);
setTheMarging();
}
else
ft.add(R.id.fragment_place, fragmentExtra, null);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current tab 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 tab position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
public static class HomePageFragment extends Fragment
{
public static final String ARG_SECTION_NUMBER = "placeholder_text";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.home_page, container, false);
}
}
public static class ExtrasFragment extends Fragment
{
public static final String ARG_SECTION_NUMBER = "placeholder_text";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.extras, container, false);
}
}
Thanks for helping

where can I write the java code in fragments?

iam a beginner in android
i wanted to make tabs
i took the sample and edited it to make a layout for every tab
but i couldn't find where to put the listeners of buttons of each layout of each tab in the code !
public class Game extends FragmentActivity implements ActionBar.TabListener {
static int Tab_no ;
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setTag("round").setText("Round").setTabListener(this));
actionBar.addTab(actionBar.newTab().setTag("score").setText("Score").setTabListener(this));
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) { // 3ashan law rege3na men ay makan yrg3ny le mkany
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) { // 3ashan law killed yrg3ny tany le makany
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
getActionBar().getSelectedNavigationIndex());
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the container
Fragment fragment = new SectionFragment();
Tab_no = tab.getPosition() + 1 ;
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class SectionFragment extends Fragment {
public SectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (Tab_no==1)
{
return inflater.inflate(R.layout.round , container, false);
}
else {
return inflater.inflate(R.layout.score , container, false);
}
}
}
}
and sorry for my bad english ! :)
You can write within onCreateView()
public class fragmentname extends Fragment{
Activity referenceActivity;
View parentHolder;
Button backBtn;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
referenceActivity = getActivity();
parentHolder = inflater.inflate(R.layout.yourlayout, container,
false);
backBtn = (Button) parentHolder.findViewById(R.id.back_btn);
backBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return parentHolder;
}
}

onCreateView() method of ViewPager's childFragment not being called

MainActivity.java
public class MainActivity extends SherlockFragmentActivity {
static MyListfragment mf;
ViewPager mpager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mf = new MyListfragment();
ft.add(android.R.id.content,mf).commit();
}}
MyListfragment.java
public class MyListfragment extends SherlockListFragment {
MyDisplayfragment tempFrag;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Connector.selection = position;
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
if(position==0)
{
tempFrag=new MyDisplayfragment();
tempFrag.setLayout(R.layout.law);
subFragmentAdapter mAdapter = new subFragmentAdapter(getChildFragmentManager());
tempFrag.setViewPagerAdapter(mAdapter);
}
ft.replace(android.R.id.content,tempFrag);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
setListAdapter(new ArrayAdapter<String>(getActivity(),
layout, Connector.list));
}}
MyDisplayfragment.java
public class MyDisplayfragment extends SherlockFragment {
int resource;
FragmentPagerAdapter mAdapter;
ViewPager v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if(Connector.selection==-1)
resource=R.layout.displayfragment;
return inflater.inflate(resource, container, false);
}
public void setViewPagerAdapter(FragmentPagerAdapter x)
{
mAdapter=x;
}
public void setLayout(int layout)
{
resource=layout;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
ViewPager pager=(ViewPager) view.findViewById(R.id.mpager);
pager.setAdapter(mAdapter);
}}
subFragment.java
public final class subFragment extends SherlockFragment {
private int layout;
public static subFragment newInstance(int content) {
subFragment fragment = new subFragment();
fragment.layout=content;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(layout,container,false);
}}
subFragmentAdapter.java
public class subFragmentAdapter extends FragmentPagerAdapter{
int[] LAYOUT={R.layout.cccc,R.layout.aaaa,R.layout.bbb};
private int mCount;
public subFragmentAdapter(FragmentManager fm) {
super(fm);
mCount = LAYOUT.length;
}
#Override
public Fragment getItem(int position) {
return subFragment.newInstance(LAYOUT[position]);
}
#Override
public int getCount() {
return mCount;
}
}
Connector.java
public class Connector {
static int selection = -1;
static String list[] = { "Law" };}
In the above project
1)MyListfragment.java is used for navigation
2)MyDisplayfragment.java is used to display according to selection made in MyListFragment
3)Connector.java is used to communicate between the above two fragments
4)subFragment.java is used to populate Viewpager with Fragments
5)subFragmentAdapter.java is th adapter for Viewpager
When i run this project the viewpager seems to be blank and doesnot show any of the child fragments and after debugging i saw that onCreateView() method of subFragment.java is not called.
My question is why the onCreateView() method is not being called
Please refer to Luksprog's comment for the answer.

Categories

Resources