Overlapping fragment with activity view - android

I am following a fragment example https://gist.github.com/daichan4649/2947119.
I am adding the fragment dynamically after button click event.But the fragment is overlapping with the button. And when I am pressing back key on this screen, activity is closed.
Need help to display only the fragment after button is clicked and if the back is pressed after adding fragment, then only the top fragment should be closed.
Here are my test code.
MainActivity.java
public class MainActivity extends FragmentActivity {
private static Button mBtn;
private static final String TAG_LIST = "list";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
return;
}
mBtn = (Button) findViewById(R.id.clickme);
mBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = getFragmentManager().findFragmentByTag(TAG_LIST);
if (fragment == null) {
fragment = TestListFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(android.R.id.content, fragment, TAG_LIST);
ft.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;
}
}
TestListFragment.java
public class TestListFragment extends ListFragment {
public static TestListFragment newInstance() {
return new TestListFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
ViewGroup rootView = (ViewGroup) inflater.inflate(android.R.id.content, container, false);
return rootView;
}
#SuppressLint("NewApi")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_column, R.id.text);
setListAdapter(adapter);
adapter.addAll(createDataList(10));
}
private static List<String> createDataList(int counts) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < counts; i++) {
list.add("i=" + i);
}
return list;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//Toast.makeText(getActivity(), "List Item Clicked", Toast.LENGTH_SHORT).show();
//On item click, launch the DialogFragment
TestDialogFragment moveFragment = new TestDialogFragment( );
moveFragment.show(getFragmentManager(), "Test List Fragment");
}
TestDilogFragment.java
public class TestDialogFragment extends DialogFragment {
private View testDialogFragment = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Fill the layout as per Your requirement
testDialogFragment = inflater.inflate(R.layout.activity_list_fragment, container);
return testDialogFragment;
}
}
activity-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=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/clickme"
android:text="ClickMe" />
</RelativeLayout>
activity_list_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"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>

Change your activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parentt" >
<Button
android:id="#+id/clickme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<FrameLayout
android:id="#+id/container"
android:layout_above="#id/clickme"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
>
</FrameLayout>
</RelativeLayout>
You have a Button at the bottom and a ViewGroup which is a FrameLayout at the top. You add the Fragment to the container.
And in ManiActivtiy change to
ft.add(R.id.container, fragment, TAG_LIST);

Related

Google Map slow after displaying a fragment

I am displaying various fragments in an Activity FrameLayout. The first fragment I display is a Google Map. To display a fragment, I swap the FrameLayout with a fragment. Next I display a fragment then push to the backstack. Upon popping the backstack the Google Map becomes very slow and laggy. If I override onBackPressed, remove the pushed fragment from the backstack then recreate the Google Map fragment, the Google Map responds as expected. Overridding onBackPressed seems like a work around.
How come the map is slow and laggy?
Here is my code (without the onBackPressed function I mentioned):
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayFragment(new MapFragment());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
try {
int id = item.getItemId();
if(id == R.id.displayBlankFragment) {
displayDialogFragment(new BlankFragment());
return true;
}
} catch(Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
private void displayFragment(Fragment fragment) {
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.frame, fragment);
t.commit();
}
private void displayDialogFragment(Fragment fragment) {
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.frame, fragment);
t.addToBackStack(null);
t.commit();
}
}
activity_main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
MapFragment
public class MapFragment extends Fragment {
private View view;
public MapFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(view == null) {
view = inflater.inflate(R.layout.fragment_map, container, false);
}
return view;
}
}
fragment_map.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" >
</fragment>
</FrameLayout>
BlankFragment
public class BlankFragment extends Fragment {
public BlankFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
fragment_blank.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment"/>
</FrameLayout>

How to set onclick listener for a button in a fragment in android

My app contains a form as shown in the following image:
When I click on menu options button, the drawer opens as shown in the following image:
I want the drawer to open when the button select location is pressed.
My codes are
RegisterBlood.java
...
public class RegisterBlood extends Activity implements OnItemClickListener {
DrawerLayout dLayout, dLayout2;
ListView dList, dList2;
ArrayAdapter<String> adapter, adapter2;
String[] state_data2;
String city = "", state = "";
Button location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectlocation);
Bundle args = new Bundle();
Fragment detail = new RegisterBloodFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail)
.commit();
...
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, state_data);
dList.setAdapter(adapter);
dList.setSelector(android.R.color.holo_blue_dark);
// dLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
dList.setOnItemClickListener(this);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// your action...
if (!dLayout.isDrawerOpen(dList)) {
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, state_data2);
dList.setAdapter(adapter);
dLayout.openDrawer(dList);
dList.setOnItemClickListener(this);
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your action...
if (dLayout.isDrawerOpen(dList)) {
dLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
return true;
}
return super.onKeyDown(keyCode, e);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, final int position,
long id) {
// TODO Auto-generated method stub
...
dLayout2 = (DrawerLayout) findViewById(R.id.drawer_layout);
dList2 = (ListView) findViewById(R.id.left_drawer);
adapter2 = new ArrayAdapter<String>(RegisterBlood.this,
android.R.layout.simple_list_item_1, city_data);
dList2.setAdapter(adapter2);
dList2.setSelector(android.R.color.holo_blue_dark);
dLayout2.openDrawer(dList2);
dLayout2.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
dList2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position2,
long id) {
dLayout2.closeDrawers();
state = state_data2[position];
city = city_data[position2];
Bundle args = new Bundle();
args.putString("Menu", city_data[position2] + " ("
+ state_data2[position] + ")");
Fragment detail = new RegisterBloodFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, detail).commit();
}
});
}}
RegisterBloodFragment.java
...
public class RegisterBloodFragment extends Fragment implements OnClickListener {
Button location;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
View view = inflater.inflate(R.layout.registerblood, container, false);
String menu = getArguments().getString("Menu");
location= (Button) view.findViewById(R.id.etlocation);
location.setText(menu);
//Context c=getActivity();
//location.setOnClickListener(c.getApplicationContext().set);
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"Yes",
Toast.LENGTH_SHORT).show();
}
}
registerblood.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/silver"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="10dp"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:paddingTop="10dp" >
<EditText
android:id="#+id/bregetName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:ems="10"
android:hint="Name" />
<EditText
android:id="#+id/bregetBloodGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:ems="10"
android:hint="Blood Group" />
<Button
android:id="#+id/etlocation"
style="#android:style/Widget.EditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:ems="10"
android:hint="select location" >
</Button>
<Button
android:id="#+id/bregbtnSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10sp"
android:layout_marginTop="10sp"
android:background="#drawable/button"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:text="Submit"
android:textColor="#FFFFFF"
android:textSize="24sp" />
</LinearLayout>
selectlocation.xml
<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">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#fff"/>
My question is:
How to add onclicklistener for select location button in RegisterBlood.java or call onClickListener which is in RegisterBlood.java from RegisterBloodFragment.java ?
Please help me out.
Since the button is a part of the fragment's layout, set the listener there:
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
View view = inflater.inflate(R.layout.registerblood, container, false);
String menu = getArguments().getString("Menu");
location = (Button) view.findViewById(R.id.etlocation);
location.setText(menu);
location.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
RegisterBlood activity = (RegisterBlood) getActivity();
// Now you can contact your activity through activity e.g.:
activity.onKeyDown(KeyEvent.KEYCODE_MENU, null);
}
First of all remember to implements the OnClickListener interface:
public class YourClassName extends Fragment implements View.OnClickListener
public Button button;
Then, inside the method OnCreateView, inflate the button and set the listener to it, like this:
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
button = (Button) inflater.inflate(R.layout.registerblood, container, false).findViewById(R.id.your_button_id);
button.setOnClickListener(this);
}
Then #Override the function onClick and do whatever you gotta do:
#Override
public void onClick(View v) {
//YOUR CODE HERE
}
EDIT
If you're simply looking for a FocusListener (in that case your question needs an update) set the listener on your onCreateView method:
your_edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
Toast.makeText(getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
// OPEN THE DRAWER HERE
} else {
Toast.makeText(getApplicationContext(), "lost the focus", Toast.LENGTH_LONG).show();
}
}
or you can implement that listener to your class.
u need to inflate fragment like this for button click
View view = inflater.inflate(R.layout.fragment_blank3,
container, false);
Button bt1=(Button)view.findViewbyId(R.id.buttton);
bt1.setOnclick...
//then return in on create view.
return view;
// this works good, thankyou

Laggy switching between fragments using a drawerlayout - android

I'm encountering slow/laggy behaviour when swithcing between frgaments using a drawerlayout. I've read up here on stackoverflow and elsewhere regarding solving this issue and a major piece of advice e.g. as seen here is to populating bits of fragment related views elsewhere hence my question of how best can one do the populating part outside of onCreateView() to avoid the laggy behaviour.
Any help is appreciated.
My code is as follows:
My main activity below:
/*! Main activity class */
public class MainActivity extends ActionBarActivity implements FragListener {
/** Private vars */
private DrawerLayout drawerLayout;
private ListView lvDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private CharSequence drawerTitle;
private CharSequence title;
private DrawerLayoutAdapter drawerLayoutAdapter;
private List<DrawerLayoutDrawer> lvDrawerLayoutData;
/** Public vars */
public static String TAG = "MainActivity";
public MainActivity mainActivity;
public Display display;
public Typeface officialBoldFont, officialRegularFont;
public TextView actionBarTView, tvActionBarTitle = null;
public Fragment fragment;
//!<
public MainActivity() {
}
//!<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// getTitle() is part of Activity
title = drawerTitle = getTitle();
// Obtain the normal device display area
display = getWindowManager().getDefaultDisplay();
// Set official font
officialRegularFont = Typeface.createFromAsset(this.getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(this.getAssets(), "square721extendedbold.ttf");
// Show action bar
getSupportActionBar().show();
// Inflate the custom action bar
LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mCustomActionView = inflator.inflate(R.layout.actionbar_layout, null);
tvActionBarTitle = (TextView) mCustomActionView.findViewById(R.id.tv_action_bar_title);
tvActionBarTitle.setTypeface(officialBoldFont);
tvActionBarTitle.setTextColor(Color.parseColor("#000000"));
tvActionBarTitle.setTextSize(14.5f);
getSupportActionBar().setCustomView(mCustomActionView);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xffFFCC00));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
// Inflate and customise the drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setDrawerShadow(new ColorDrawable(0xffFF0000), GravityCompat.START);
drawerLayout.setBackgroundResource(R.drawable.bgnd_drawerlayout_default);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(title);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
// Inflate and customise the drawer layout list and drawer layout adapter
lvDrawerLayout = (ListView) findViewById(R.id.lv_drawer);
lvDrawerLayout.setDividerHeight(2);
// Below is the listview's bgnd and is different from bgnd_lv_item_drawerlayout.xml which is the bgnd for the items in this LV
lvDrawerLayout.setBackgroundResource(R.drawable.bgnd_lv_drawerlayout_default);
lvDrawerLayoutData = new ArrayList<DrawerLayoutDrawer>();
lvDrawerLayoutData.add(new DrawerLayoutDrawer("ADMINISTRATION", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("FINANCE CALCULATOR", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("EXIT", R.drawable.ic_test));
drawerLayoutAdapter = new DrawerLayoutAdapter(this, R.layout.lv_layout_drawer, lvDrawerLayoutData, officialRegularFont, officialBoldFont);
lvDrawerLayout.setAdapter(drawerLayoutAdapter);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Call starting fragment
if (savedInstanceState == null) {
callStartingFrag(0);
}
}
//!< Call starting fragment
public void callStartingFrag(int position) {
Bundle args = new Bundle();
fragment = new FragmentOne();
args.putString(" ", lvDrawerLayoutData.get(position).getItemName());
args.putInt(" ", lvDrawerLayoutData.get(position).getImgResID());
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
//!< Enable drawer layout
public void enableDrawerLayout() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
//!< Set custom action bar title
public void setActionBarTitle(String title){
tvActionBarTitle.setText(title);
}
//!< Return MainActivity object
public MainActivity getMainActivity() {
mainActivity = new MainActivity();
return mainActivity;
}
//!< This hook is called whenever an item in your options menu is selected. . The action bar home/up action should open or close the drawer. ActionBarDrawerToggle will take care of this.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
//!< Sync the toggle state after onRestoreInstanceState has occurred. Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
//!< Pass any configuration change to the drawer toggles. This method should always be called by your Activity's onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
//!< Call respective fragment
public void selectItem(int position) {
switch (position) {
case 0:
fragment = new FragmentTwo();
break;
case 1:
fragment = new FragmentThree();
break;
case 2:
finish();
break;
default:
break;
}
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
}
Drawer layout code:
<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="fill_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/lv_drawer"
android:layout_width="240dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#000000"/>
</android.support.v4.widget.DrawerLayout>
Drawer layout listview laout code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:id="#+id/itemLayout">
<TextView
android:id="#+id/tv_itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
Action bar layout code:
<?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="#android:color/transparent" >
<TextView
android:id="#+id/tv_action_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:textSize="15dp"
android:maxLines="1"
android:ellipsize="end"/>
</RelativeLayout>
1st fragment code:
public class FragmentOne extends Fragment {
ImageView ivIcon;
TextView tvAgentID;
public Typeface officialBoldFont, officialRegularFont;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_one, container, false);
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag one list item 1", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragOneClickListener());*/
//
officialRegularFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedbold.ttf");
tvAgentID = (TextView) view.findViewById(R.id.tv_agentid);
tvAgentID.setText("TESTING 1 2 3");
tvAgentID.setTypeface(officialBoldFont);
tvAgentID.setTextColor(Color.BLACK);
tvAgentID.setBackgroundColor(Color.WHITE);
tvAgentID.setTextSize(25f);
return view;
}
}
1st fragment layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#000000">
<LinearLayout
android:id="#+id/ll_innerloginlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="20dp"
android:padding="20dp">
<TextView
android:id="#+id/tv_agentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
2nd fragment code below:
public class FragmentTwo extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
private List<DrawerLayoutDrawer> dataList;
public FragmentTwo()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_two, container, false);
//
((MainActivity) getActivity()).setActionBarTitle("Test screen 2");
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag two list item 2", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragTwoClickListener());*/
ivIcon=(ImageView)view.findViewById(R.id.frag2_icon);
tvItemName=(TextView)view.findViewById(R.id.frag2_text);
tvItemName.setText("TESTING FRAG TWO");
tvItemName.setTextSize(45f);
tvItemName.setTextColor(Color.RED);
tvItemName.setBackgroundColor(Color.BLACK);
return view;
}
}
2nd fragment XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag2_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag2_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="200dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="12dp"
android:paddingBottom="0dp"/>
</LinearLayout>
3rd fragment code:
public class FragmentThree extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentThree()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_three, container, false);
ivIcon=(ImageView)view.findViewById(R.id.frag3_icon);
tvItemName=(TextView)view.findViewById(R.id.frag3_text);
tvItemName.setText("TESTING FRAG THREE");
return view;
}
}
3rd fragment XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag3_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag3_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
1st fragment listener:
public class FragOneClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragOneSelectItem(position);
}
}
2nd fragment listener:
public class FragTwoClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragTwoSelectItem(position);
}
}

Get view for button click on the Fragment of the ViewPager

I have successfully set up the a FragmentActivity with FragementPagerAdapter associated with ViewPager to implement two tabbed application .
One of the Tabs namely "Wave" has a text view and a button . All I want is call textview.setText method via the onClick method of button described by its xml attribute .
I do not know where should I initialize my TextView or Button , how can I get the context of Wave tab and where should I write onclick method-
public class InformationShow extends FragmentActivity {
XMLdata dataObject;
ViewPager viewPager;
PagerAdapter adpt;
Fragment temp;
TextView tv;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewPager=(ViewPager)findViewById(R.id.pager);
adpt = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adpt);
// temp=adpt.fg.findFragmentById((int)adpt.getItemId(1));
tv=(TextView)findViewById(R.id.graphWaveTextView);
bt = (Button)findViewById(R.id.button1);
}
public void changeText(View v){
tv.setText("It worked ");
}
Adapter Class
public class PagerAdapter extends FragmentPagerAdapter {
int count = 2;
CharSequence namme[] = {"Temperature","Wave"};
XMLdata data;
FragmentManager fg;
public PagerAdapter(FragmentManager fragmentManager ){
super(fragmentManager);
this.fg = fragmentManager;
}
Context context;
#Override
public Fragment getItem(int arg0) {
switch (arg0){
case 0:{
TemperatureGraphFrag temp = new TemperatureGraphFrag();
return temp;
}
case 1:{WaveHeightGraphFrag wave = new WaveHeightGraphFrag();
return wave;
}
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return namme[position];
}
}
Fragments Class
public class TemperatureGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_t, container, false);
return view;
}
}
public class WaveHeightGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_sig_wave_height, container, false);
return view;
}
}
fragment_main XML implemented by FragmentActicity
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#65C2C9"
android:scrollbarSize="5dp"/>
</android.support.v4.view.ViewPager>
Tab 2 Fragment XML graph_sig_wave_height
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/graphWaveTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_gravity="center"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center"
android:onClick="changeText"/>
</LinearLayout>
Tab 1 fragment layout XML graph_t
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linearTemp"
>
<TextView
android:id="#+id/graphTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_gravity="center"
/>
</LinearLayout>
Add the following method to your WaveHeightGraphFrag class:
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
final TextView t = (TextView) view.findViewById(R.id.graphWaveTextView);
Button b = (Button) view.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
t.setText("It worked ");
}
});
}
This is what you want.

How to inflate view inside fragment

If I try to inflate a view within a fragment I am getting NULL.. For example:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Here I will inflate my view using the layout ID & return.
return view;
}
Whenever a button is clicked I need to create a dynamic view e.g.: button & add to the LinearLayout. I would like to perform this operation inside my fragment class like this:
public void addPlaces() {
Button button = new Button(null);
button.setText("button name");
// e.g. like adding button to enter code here linear layout
linearLayout.addView(button);
}
So, if I get inflate LinearLayout inside onCreateView and use it in add class, I'm getting NULL. How to achieve?
Declare the variable as a instance variable and then initialize Linear Layout
LinearLayout linearLayout;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
return rootView;
}
Then
public void addPlaces() {
Button button = new Button(getActivity());
// needs activity context
// fragment hosted by a activity. use getActivity() to get the context of the hosting activity.
button.setText("button name");
linearlayout.addView(button);
}
Example: Modify the below according to your requirement.
fragment1.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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<LinearLayout
android:layout_width="fill_parent"
android:id="#+id/linearlayout"
android:layout_height="fill_parent"
android:layout_above="#+id/button1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
Myfragment.java
public class Myfragment extends Fragment {
LinearLayout linearLayout;
View rootView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPlaces();
}
});
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
public void addPlaces() {
Button button = new Button(getActivity()); // needs activity context
button.setText("button name");
linearLayout.addView(button);
}
}
Snap shot of my emulator
Edit :
activity-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=".MainActivity" >
<fragment android:name="com.example.fragments.Myfragment"
android:id="#+id/frag"
android:layout_above="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends FragmentActivity {
Button b;
Myfragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment = new Myfragment();
fragmentTransaction.add(R.id.frag, fragment);
fragmentTransaction.commit();
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fragment.addPlaces();
}
});
}
}
Myfragment.java
public class Myfragment extends Fragment {
LinearLayout linearLayout;
View rootView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
public void addPlaces() {
Button button = new Button(getActivity()); // needs activity context
button.setText("button name");
linearLayout.addView(button);
}
}

Categories

Resources