In my app in need to hide layout when i click out side (MobileFragment) of that layout. You can understand the whole problem from given below images.
This is my app sturcture:
This is the problem:
Here is my code:
MainActivity.java
package com.example.admin.smsrupee;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TabLayout tabLayout;
private ViewPager viewPager;
private ImageView menu_icon,profile_icon;
private LinearLayout layout,profile_layout;
ViewPagerFinder adapter;
CoordinatorLayout coordinatorLayout;
private int[] tabIcons = {
R.drawable.mobile_icon,
R.drawable.dth_icon,
R.drawable.data_card_icon,
R.drawable.landline_icon,
R.drawable.electricity_icon,
R.drawable.gas_icon
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager)findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
menu_icon = (ImageView)findViewById(R.id.menu_icon);
profile_icon = (ImageView)findViewById(R.id.profile_icon);
layout = (LinearLayout)findViewById(R.id.menu_list);
profile_layout = (LinearLayout)findViewById(R.id.profile_menu_list);
menu_icon.setOnClickListener(this);
profile_icon.setOnClickListener(this);
viewPager.setOnClickListener(this);
coordinatorLayout.setOnClickListener(this);
setupTabIcons();
FragmentStatePagerAdapter a = (FragmentStatePagerAdapter)viewPager.getAdapter();
Fragment ft = (Fragment)a.instantiateItem(viewPager, viewPager.getCurrentItem());
System.out.println("Fragment---" + ft);
}
private void setupTabIcons() {
Drawable mobile_img;
Resources res1 = getResources();
mobile_img = ContextCompat.getDrawable(MainActivity.this, R.drawable.mobile_icon);
mobile_img.setBounds(0, 0, 20, 25);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("Mobile");
tabOne.setCompoundDrawables(null,mobile_img, null, null);
tabLayout.getTabAt(0).setCustomView(tabOne);
Drawable dth_img ;
Resources res2 = getResources();
dth_img = ContextCompat.getDrawable(MainActivity.this, R.drawable.dth_icon);
dth_img.setBounds(0, 0, 20, 25);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("DTH");
tabTwo.setCompoundDrawables(null, dth_img, null, null);
tabLayout.getTabAt(1).setCustomView(tabTwo);
Drawable data_img ;
Resources res3 = getResources();
data_img = ContextCompat.getDrawable(MainActivity.this, R.drawable.data_card_icon);
data_img.setBounds(0, 0, 20, 25);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText("Data Card");
tabThree.setCompoundDrawables(null, data_img, null, null);
tabLayout.getTabAt(2).setCustomView(tabThree);
Drawable landline_img ;
Resources res4 = getResources();
landline_img = ContextCompat.getDrawable(MainActivity.this, R.drawable.landline_icon);
landline_img.setBounds(0, 0, 20, 25);
TextView tabFour = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabFour.setText("LandLine");
tabFour.setCompoundDrawables(null,landline_img, null, null);
tabLayout.getTabAt(3).setCustomView(tabFour);
Drawable electricity_img ;
Resources res5 = getResources();
electricity_img = ContextCompat.getDrawable(MainActivity.this, R.drawable.electricity_icon);
electricity_img.setBounds(0, 0, 20, 25);
TextView tabFive = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabFive.setText("Electricity");
tabFive.setCompoundDrawables(null,electricity_img, null, null);
tabLayout.getTabAt(4).setCustomView(tabFive);
Drawable gas_img ;
Resources res6 = getResources();
gas_img = ContextCompat.getDrawable(MainActivity.this, R.drawable.gas_icon);
gas_img.setBounds(0, 0, 20, 25);
TextView tabSix = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabSix.setText("Gas");
tabSix.setCompoundDrawables(null,gas_img , null, null);
tabLayout.getTabAt(5).setCustomView(tabSix);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerFinder(getSupportFragmentManager());
adapter.addFragment(new MobileFragment(), "Mobile");
adapter.addFragment(new DTHFragment(), "DTH");
adapter.addFragment(new DataCardFragment(), "Data Card");
adapter.addFragment(new LandLineFragment(), "Landline");
adapter.addFragment(new ElectricityFragment(), "Electricity");
adapter.addFragment(new GasFragment(), "Gas");
viewPager.setAdapter(adapter);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.menu_icon:
if(layout.getVisibility() == View.INVISIBLE){
layout.setVisibility(View.VISIBLE);
}else{
layout.setVisibility(View.INVISIBLE);
}
break;
case R.id.profile_icon:
if(profile_layout.getVisibility() == View.INVISIBLE) {
profile_layout.setVisibility(View.VISIBLE);
} else {
profile_layout.setVisibility(View.INVISIBLE);
}
break;
default:
break;
}
}
class ViewPagerFinder extends FragmentStatePagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerFinder(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position){
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public Fragment returnFragment(int position){
return mFragmentList.get(position);
}
}
#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);
}
}
MobileFragemnt.java
package com.example.admin.smsrupee;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
/**
* Created by admin on 11/4/2015.
*/
public class MobileFragment extends android.support.v4.app.Fragment {
EditText editText;
private ImageView menuicon;
private LinearLayout layout;
private RelativeLayout relativeLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.mobile_fragment, container, false);
return view;
}
public static MobileFragment newInstance(int index) {
MobileFragment f = new MobileFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
}
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"
android:id="#+id/cordinator"
android:clickable="true"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent" 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:contentInsetStart="0dp"
android:contentInsetLeft="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay">
<include layout="#layout/content_main"/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#2f5392"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_marginTop="50dp"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
</android.support.v4.view.ViewPager>
<!--<include layout="#layout/dummy_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>-->
<include layout="#layout/menu_contents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
<include layout="#layout/profile_contents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
mobile_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mobile_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.androidhive.materialtabs.fragments.OneFragment">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#2f5392"
android:id="#+id/view" />
<LinearLayout
android:layout_width="wrap_content"
android:id="#+id/linearlayout_one1"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prepaid"
android:textColor="#2f5392"
android:layout_marginRight="20dp"
android:id="#+id/prepaid_radio1"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:textColor="#2f5392"
android:layout_height="wrap_content"
android:text="Postpaid"
android:id="#+id/postpaid_radio1"
android:checked="false" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:id="#+id/linearlayout_two1"
android:layout_below="#+id/linearlayout_one1"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="20dp"
android:orientation="vertical"
>
<EditText
android:layout_width="300dp"
android:hint="Enter Your Mobile Number"
android:textSize="15sp"
android:text="123xxxxxx"
android:id="#+id/mobile_number1"
android:paddingLeft="30dp"
android:layout_height="wrap_content"
android:drawableRight="#drawable/editbox_icon"
/>
<EditText
android:layout_width="300dp"
android:hint="Select Operator"
android:paddingLeft="30dp"
android:id="#+id/operator1"
android:textSize="15sp"
android:layout_height="wrap_content"
android:drawableRight="#drawable/down_arrow"
/>
<EditText
android:layout_width="300dp"
android:drawableLeft="#drawable/indian_rupee"
android:hint=" Amount"
android:id="#+id/amount1"
android:textSize="15sp"
android:layout_height="wrap_content"
android:drawableRight="#drawable/browse_plan"
/>
</LinearLayout>
<Button
android:layout_below="#+id/linearlayout_two1"
android:layout_marginTop="35dp"
android:layout_width="250dp"
android:id="#+id/proceed1"
android:layout_centerHorizontal="true"
android:layout_height="37dp"
android:background="#2f5392"
android:textColor="#ffffff"
android:text="PROCEED"/>
</RelativeLayout>
content_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"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/relative_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/sms_rupee_logo"
/>
<ImageView
android:id="#+id/menu_icon"
android:layout_width="wrap_content"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:layout_height="wrap_content"
android:src="#drawable/menu_icon"
/>
<ImageView
android:id="#+id/wallet_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/menu_icon"
android:src="#drawable/wallet_icon" />
<ImageView
android:id="#+id/profile_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/wallet_icon"
android:src="#drawable/profile_icon" />
</RelativeLayout>
</RelativeLayout>
profile_content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/profile_menu_list"
android:layout_width="165dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:clickable="true"
android:layout_alignParentTop="true"
android:background="#2f5392"
android:orientation="vertical"
android:visibility="invisible"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:layout_height="wrap_content"
android:src="#drawable/add_user"/>
<TextView
android:id="#+id/register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:text="Register"
android:textColor="#fff"
android:textSize="17dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:padding="8dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#drawable/login"/>
<TextView
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="3dp"
android:padding="8dp"
android:text="Login"
android:textColor="#ffffff"
android:textSize="17dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:padding="8dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#drawable/referral"/>
<TextView
android:id="#+id/referrals"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:text="Referrals"
android:textColor="#ffffff"
android:textSize="17dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:padding="8dp"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
android:src="#drawable/recharge"/>
<TextView
android:id="#+id/configure_easychange"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:text="Configure EasyCharge"
android:textColor="#ffffff"
android:textSize="17dp"
/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Firstly, you can get an instance of an Activity inside its fragment by help of getActivity() method. Use this instance to call any method of the activity from your fragment like this :-
((MainActivity) getActivity()).methodName();
Secondly, I would suggest you to convert that bar into a NavigationDrawer which will benefit you by providing you with a much cleaner user interface with more cleaner transitions.
MainActivity
public class HomeActivity extends AppCompatActivity {
public static BottomNavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//-----------------------------------------------| Bottom navigation menu
mNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
mNavigationView.setOnNavigationItemSelectedListener(new ActionHandler());
}
private class ActionHandler implements BottomNavigationView.OnNavigationItemSelectedListener {
//-----------------------------------------------| Bottom navigation menu listener
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_menu:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_left, 0).add(android.R.id.content, new MenuFragment(), "myFragmentTag").addToBackStack("tag").commit(); // without FrameLayout
return true;
case R.id.action_account:
//
return true;
}
return false;
}
}
}
fragment_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/root_view"
android:background="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".views.fragments.MenuFragment">
<LinearLayout
android:orientation="vertical"
android:layout_marginEnd="150dp"
android:background="#color/colorBackgroundGrey"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:background="#color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="250dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/header_photo"
app:civ_border_width="1dp"
app:civ_border_color="#color/colorLightGrey"
app:tint="#color/colorWhite"
android:src="#drawable/ic_add_photo"
android:layout_centerInParent="true"
android:layout_width="140dp"
android:layout_height="140dp"/>
<TextView
android:id="#+id/nav_header_title"
android:textColor="#color/colorWhite"
android:layout_marginTop="10dp"
android:text="#string/app_name"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginBottom="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/items_recycler_view"
tools:listitem="#layout/item_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
MemuFragment
public class MenuFragment extends Fragment {
private UserModel mUser;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
//getActivity().onBackPressed();
((RelativeLayout) view.findViewById(R.id.root_view)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Utility.getInstance().onBackFragment(Objects.requireNonNull(getActivity()).getSupportFragmentManager(), new MenuFragment());
}
});
return view;
}
}
Utility
public class Utility {
private String TAG = this.getClass().getSimpleName();
private static Utility mUtility;
public static Utility getInstance() {
if (mUtility == null) {
mUtility = new Utility();
}
return mUtility;
}
//===============================================| Add fragment | Replace fragment | Remove fragment
//https://stackoverflow.com/questions/18634207/difference-between-add-replace-and-addtobackstack
public void onAddFragment(FragmentManager mManager, Fragment mFragment){
//getSupportFragmentManager().beginTransaction().add(android.R.id.content, new FragmentHome(), "myFragmentTag").addToBackStack("tag").commit(); // without FrameLayout
mManager.beginTransaction().setCustomAnimations(R.anim.fragment_fade_enter, 0).add(R.id.home_container, mFragment).addToBackStack(mFragment.getTag()).commitAllowingStateLoss(); //with back press
//getActivity().getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fragment_fade_enter, 0).replace(layout, mFragment).addToBackStack(mFragment.getTag()).commitAllowingStateLoss(); //with back press
}
public void onReplaceFragment(FragmentManager mManager, Fragment mFragment){
mManager.beginTransaction()
.setCustomAnimations(R.anim.fragment_fade_enter, 0)
.replace(R.id.home_container, mFragment)
.addToBackStack(null)
.commit();
}
public void onRemoveFragment(FragmentManager mFragmentManager, Fragment mFragment){
mFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.fragment_fade_enter, 0)
.remove(mFragment)
.addToBackStack(null)
.commit();
}
public void onBackFragment(FragmentManager mFragmentManager, Fragment mFragment){
if(mFragmentManager.getBackStackEntryCount() > 0) {
mFragmentManager.popBackStack(mFragment.getTag(), 0);
//getActivity().getSupportFragmentManager().popBackStack(new CampaignFragment().getTag(), 0);
}
}
public void onShowFragmentDialog(FragmentManager mFragmentManager, BottomSheetDialogFragment mFragment){
mFragment.setCancelable(false);
mFragment.show(mFragmentManager, mFragment.getTag());
}
}
Related
Hello I am developing an app that fetches data from the server the code is shown below
XML:-
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ImageQuiz">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar1"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="8dp"
app:title="QUIZ"
app:titleTextColor="#fff" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e2e2e2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="8dp"
app:title="QUIZ"
app:titleTextColor="#fff"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView13"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Answer these questions"
android:textSize="10dp"
android:textAlignment="center"
android:padding="5dp"
android:textColor="#fff"
android:background="#05af43"
/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recylcerViewImage"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Submit"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:textColor="#585858"
android:background="#drawable/rounded_corner"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
ImageQuizAdapter.java
package com.accolade.eventify;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import com.bumptech.glide.Glide;
import java.util.List;
public class ImageQuizAdapter extends RecyclerView.Adapter<ImageQuizAdapter.ImageQuizViewHolder> {
private Context mCtx;
private List<ImageQuizModel> quizList;
public ImageQuizAdapter (Context mCtx, List<ImageQuizModel> quizList) {
this.mCtx = mCtx;
this.quizList = quizList;
}
#Override
public ImageQuizViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_recycler_image_quiz, null);
return new ImageQuizViewHolder(view);
}
#Override
public void onBindViewHolder(ImageQuizViewHolder holder, int position) {
ImageQuizModel imageQuizModel=quizList.get(position);
Glide.with(mCtx)
.load(imageQuizModel.getImage())
.into(holder.imageView);
//here i used only image
}
#Override
public int getItemCount() {
return quizList.size();
}
public class ImageQuizViewHolder extends RecyclerView.ViewHolder {
RadioButton r1,r2,r3,r4;
ImageView imageView;
public ImageQuizViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView2);
r1 = itemView.findViewById(R.id.radio_button1);
r2 = itemView.findViewById(R.id.radio_button2);
r3 = itemView.findViewById(R.id.radio_button3);
r4 = itemView.findViewById(R.id.radio_button4);
}
}
}
ImagaQuiz.java
package com.accolade.eventify;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ImageQuiz extends AppCompatActivity {
private static final String URL_PRODUCTS = "http://accoladetest.cf/MyApi/MyApiQuizPic.php";
RecyclerView recyclerView;
private Toolbar mTopToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_quiz);
mTopToolbar = (Toolbar) findViewById(R.id.my_toolbar1);
setSupportActionBar(mTopToolbar);
recyclerView = findViewById(R.id.recylcerViewImage);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
loadProducts();
}
#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_quiz, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_favorite) {
Toast.makeText(this, "Add Feature", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadProducts() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
List<ImageQuizModel> data=new ArrayList<>();
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for(int i=0;i< array .length();i++){
JSONObject json_data = array .getJSONObject(i);
ImageQuizModel product = new ImageQuizModel();
product.id= json_data.getInt("id");
product.image= json_data.getString("image");
product.op1= json_data.getString("op1");
product.op2= json_data.getString("op2");
product.op3= json_data.getString("op3");
product.op4= json_data.getString("op4");
data.add(product);
}
//creating adapter object and setting it to recyclerview
ImageQuizAdapter adapter = new ImageQuizAdapter(ImageQuiz.this, data);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
}
ImageQuizModel.java
package com.accolade.eventify;
public class ImageQuizModel {
public int id;
public String image;
public String op1;
public String op2;
public String op3;
public String op4;
public ImageQuizModel(){
}
public String getImage() {
return image;
}
public int getId(){
return id;
}
public String getOp1() {
return op1;
}
public String getOp2() {
return op2;
}
public String getOp3() {
return op3;
}
public String getOp4() {
return op4;
}
}
layout_recycler_image_guiz.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
app:cardCornerRadius="10dp"
android:elevation="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="220dp"
android:scaleType="fitXY"
app:srcCompat="#drawable/img" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radio_button1"
android:text=" Option 1"
android:textSize="20dp"
android:buttonTint="#color/colorPrimary"
/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radio_button2"
android:text="Option 2"
android:textSize="20dp"
android:buttonTint="#color/colorPrimary"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radio_button3"
android:text="Option 3"
android:textSize="20dp"
android:buttonTint="#color/colorPrimary"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radio_button4"
android:text="Option 4"
android:textSize="20dp"
android:buttonTint="#color/colorPrimary"/>
</LinearLayout>
</RadioGroup>
</LinearLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
But here the problem is recycler view is displaying in half screen as the image below, I want its width to matchparent
enter image description here
I removed ConstraintLayout and instead I used RelativeLayout as a parent and it is working, Thank you guys for responding.
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="220dp"
android:scaleType="fitXY"
app:srcCompat="#drawable/img" />
</LinearLayout>
</RelativeLayout>
Go to your imageview which you are using and make sure attributes layout height and width both are set to match_parent. Hope this will help.
You should not use match_parent for widgets within a ConstraintLayout. From the documentation:
Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".
If you want a widget to span 100% across its parent, the way to do that in ConstraintLayout is to set the width of the widget to 0dp and specify a start and end constraint as follows for the RelativeLayout which is a child of the ConstraintLayout:
<RelativeLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#e2e2e2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
In short, all children of ConstraintLayout should be constrained vertically and horizontally and match_parent should not be used.
My image is not showing in the viewpager, I have the xml with viewpager at the top and recyclerview at the bottom.
I do not know if I need to do implementation with interfaces. I follow the image slider example from here at Android Studio Tutorial - 70 - Implement Swipe Views
public class Home_activity extends BaseActivity {
ViewPager viewPager;
TextView testview;
private static final String urlHome =
"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewPager = (ViewPager) findViewById(R.id.viewPager);
SwipeAdapter swipeAdapter = new
SwipeAdapter(getSupportFragmentManager());
viewPager.setAdapter(swipeAdapter);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
<--- PageFagment.java--->
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class PageFragment extends Fragment {
public PageFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
TextView textView;
View view = inflater.inflate(R.layout.image_fragment_layout, container,
false);
textView = (TextView) view.findViewById(R.id.textViewFragment);
Bundle bundle = getArguments();
final String message = Integer.toString(bundle.getInt("count "));
textView.setText("This id the " + message);
return view;
}
}
<--- SwipeAdapter.java--->
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class SwipeAdapter extends FragmentPagerAdapter {
public SwipeAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int i) {
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("count ", i + 1);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
this is the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="9">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="150dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/topbuttonlinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="btn1" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="btn1" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="btn1" />
</LinearLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/topbuttonlinearLayout"
android:layout_weight="7">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<include layout="#layout/bottom_navigation_layout" />
</FrameLayout>
</LinearLayout>
I have a simple application, with an Activity calling a Fragment.
Question I have is .. why is the Activity's button showing up on the Fragment ?
Seems to be a very simple problem .. just not able to pin point the issue !!
Activity screenshot :
Fragment Screenshot :
Notice that Activity's SUBMIT button shows up on the Fragment, but the TextView and EditText get hidden. Why ??
Activity :
package com.example.deep_kulshreshtha.toddsyndrome;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private TextInputEditText inputEditText;
private EditText editText;
private ToddSyndromeDBHelper dbHelper;
private SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// inputEditText = (TextInputEditText) findViewById(R.id.lastNameEditText);
editText = (EditText) findViewById(R.id.editText);
Button submitButton = (Button) findViewById(R.id.submitButton);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateReportFragment fragment = CreateReportFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main, fragment, "CreateFragment");
transaction.addToBackStack("CreateBackStack");
transaction.commit();
}
});
dbHelper = new ToddSyndromeDBHelper(this);
}
#Override
protected void onStop() {
super.onStop();
if(db != null) {db.close();}
}
public SQLiteDatabase getDb(){
if(db == null) {
// new ConnectionHelper().execute();
db = dbHelper.getWritableDatabase();
}
return db;
}
public void viewPatientReport(View view){
PatientReportFragment fragment = PatientReportFragment.
newInstance(editText.getText().toString());
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main, fragment, "SearchFragment");
transaction.addToBackStack("SearchBackStack");
transaction.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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectionHelper extends AsyncTask<Void, Void, SQLiteDatabase>{
#Override
protected SQLiteDatabase doInBackground(Void... params) {
db = dbHelper.getWritableDatabase();
return db;
}
}
}
Activity 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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Content xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/content_main"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="32dp"
android:fontFamily="cursive"
android:text="#string/todd_syndrome" />
<!-- <android.support.design.widget.TextInputLayout
android:id="#+id/layout_last_name"
android:layout_below="#id/headline"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/lastNameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint" />
</android.support.design.widget.TextInputLayout>-->
<EditText
android:id="#+id/editText"
android:layout_below="#id/headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint"/>
<Button
android:id="#+id/submitButton"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:layout_below="#id/editText"
android:onClick="viewPatientReport"/>
</RelativeLayout>
Fragment :
package com.example.deep_kulshreshtha.toddsyndrome;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class CreateReportFragment extends Fragment
implements View.OnClickListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
// private OnFragmentInteractionListener mListener;
String name;
boolean hallucegenicDrugs = false;
int age;
String gender;
boolean migraine = false;
private EditText editText;
private Switch switchMigraine;
private Spinner ageSpinner;
private RadioGroup group;
private Switch switchHall;
private Button saveButton;
private View.OnClickListener radioListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean checked = ((RadioButton)v).isChecked();
gender = ((RadioButton)v).getText().toString();
}
};
public CreateReportFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static CreateReportFragment newInstance(/*String param1, String param2*/) {
CreateReportFragment fragment = new CreateReportFragment();
// Bundle args = new Bundle();
// args.putString(ARG_PARAM1, param1);
// args.putString(ARG_PARAM2, param2);
// fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
// mParam1 = getArguments().getString(ARG_PARAM1);
// mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_create_report, container, false);
editText = (EditText) view.findViewById(R.id.createPersonName);
name = editText.getText().toString();
switchMigraine = (Switch) view.findViewById(R.id.migraineToggle);
switchMigraine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
migraine = false;
}
});
ageSpinner = (Spinner) view.findViewById(R.id.ageSpinner);
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 100; i++){ list.add(i); }
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getContext(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ageSpinner.setAdapter(adapter);
ageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
age = (int) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
group = (RadioGroup) view.findViewById(R.id.genderButton);
RadioButton maleRadio = (RadioButton) view.findViewById(R.id.radioMale);
maleRadio.setOnClickListener(radioListener);
RadioButton femaleRadio = (RadioButton) view.findViewById(R.id.radioFemale);
femaleRadio.setOnClickListener(radioListener);
switchHall = (Switch) view.findViewById(R.id.switchButton);
switchHall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
hallucegenicDrugs = isChecked;
}
});
saveButton = (Button) view.findViewById(R.id.saveButton);
saveButton.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
int syndromePercentage = 0;
Log.v("Deep", "Patient name : " + name);
Log.v("Deep", "Has migraine : " + migraine);
Log.v("Deep", "Patient age : " + age);
Log.v("Deep", "Patient gender : " + gender);
Log.v("Deep", "Drugs ? : " + hallucegenicDrugs);
if(migraine == true){ syndromePercentage += 25; }
if(age <= 15){ syndromePercentage += 25; }
if(gender.equals("Male")){ syndromePercentage += 25; }
if(hallucegenicDrugs == true){ syndromePercentage += 25; }
SQLiteDatabase db = ((MainActivity)getActivity()).getDb();
ContentValues values = new ContentValues();
values.put(PatientTableContract.FeedEntry.COL_NAME_PATIENT_NAME, name);
values.put(PatientTableContract.FeedEntry.COL_NAME_RISK, syndromePercentage);
db.insert(PatientTableContract.FeedEntry.TABLE_NAME, null, values);
Toast.makeText(getContext(), "Data saved successfully !", Toast.LENGTH_SHORT).show();
editText.setText("");
switchMigraine.setChecked(false);
ageSpinner.setSelection(0);
group.clearCheck();
switchHall.setChecked(false);
}
}
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"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.CreateReportFragment"
android:background="#android:color/white">
<!-- TODO: Update blank fragment layout -->
<android.support.design.widget.TextInputLayout
android:id="#+id/nameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/createPersonName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint" />
</android.support.design.widget.TextInputLayout>
<!-- <TextView
android:id="#+id/migraineText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/nameLayout"
android:text="#string/hint1"/>-->
<Switch
android:id="#+id/migraineToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hint1"
android:layout_below="#id/nameLayout"
android:checked="false"
android:layout_margin="10dp"
android:padding="10dp" />
<TextView
android:id="#+id/ageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/migraineToggle"
android:text="#string/hint2"
android:layout_margin="10dp"/>
<Spinner
android:id="#+id/ageSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:prompt="#string/hint2"
android:layout_below="#id/migraineToggle"
android:layout_toRightOf="#id/ageText"
android:layout_margin="10dp"
android:layout_marginLeft="20dp"/>
<!-- <TextView
android:id="#+id/genderText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ageText"
android:text="#string/hint3"/>-->
<RadioGroup
android:id="#+id/genderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/ageSpinner"
android:checkedButton="#+id/radioMale"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender ?"
android:layout_margin="10dp"/>
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:layout_margin="10dp"/>
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:layout_margin="10dp"/>
</RadioGroup>
<!-- <TextView
android:id="#+id/hallucinogenicText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/genderText"
android:text="#string/hint4"/>
<ToggleButton
android:id="#+id/hallucinogenicToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/hallucinogenicText"
android:hint="#string/hint4" />-->
<Switch
android:id="#+id/switchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/genderButton"
android:text="#string/hint4"
android:checked="false"
android:layout_margin="10dp"/>
<Button
android:id="#+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/switchButton"
android:text="Submit"
android:layout_margin="10dp"/>
</RelativeLayout>
Second fragment xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.PatientReportFragment"
android:background="#android:color/white">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/patientReport"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
Second Fragment :
package com.example.deep_kulshreshtha.toddsyndrome;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.deep_kulshreshtha.toddsyndrome.PatientTableContract.FeedEntry;
public class PatientReportFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
private MainActivity activity;
private String[] projection = {FeedEntry._ID, FeedEntry.COL_NAME_PATIENT_NAME,
FeedEntry.COL_NAME_RISK};
private String selection = FeedEntry.COL_NAME_PATIENT_NAME + " = ?";
// private OnFragmentInteractionListener mListener;
public PatientReportFragment() {
// Required empty public constructor
}
public static PatientReportFragment newInstance(String param1) {
PatientReportFragment fragment = new PatientReportFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textView = (TextView) view.findViewById(R.id.patientReport);
SQLiteDatabase db = ((MainActivity)getActivity()).getDb();
Cursor cursor = db.query(FeedEntry.TABLE_NAME,
projection,
selection,
new String[]{mParam1},
null,
null,
null);
if(cursor.getCount() == 0){
textView.setText("No data found");
return /*view*/;
} else {
cursor.moveToFirst();
int riskPercent = cursor.getInt(cursor.getColumnIndex(FeedEntry.COL_NAME_RISK));
textView.setText("Risk percentage : " + riskPercent );
return /*view*/;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_patient_report, container, false);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (MainActivity) context;
}
}
I've solved this by wrapping my button inside a LinearLayout.
Probable cause of the issue: It seems Button has higher z-index rendering when it comes to android and thus not wrapping it inside another layout renders the button higher than all other fragments.
<LinearLayout
android:id="#+id/register_btn_wrapper"
android:orientation="vertical"
android:layout_below="#+id/splash_logo_img"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/register_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/register"
android:textSize="#dimen/text_big"
android:paddingLeft="#dimen/btn_padding"
android:paddingStart="#dimen/btn_padding"
android:paddingRight="#dimen/btn_padding"
android:paddingEnd="#dimen/btn_padding"
android:layout_gravity="center"
android:background="#color/app_color" />
</LinearLayout>
Hope this helps.
When you bind your view in fragment it is always a better approach to bind it in the method
onViewCreated()
When you bind your view in onCreateView() you will face rendering issues.
So bind your view in onViewCreated() method and the problem should be solved
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.name_of_layout,container,false);
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//bind your view here
}
In the onCreateView of the fragment try adding this line
View view = inflater.inflate(R.layout.fragment_name, container, false);
view.setBackgroundColor(Color.WHITE);
I had a similar issue and fixed it using the above lines. Also, don't forget to add android:clickable="true" to your fragment_layout.xml parent layout.
I couldn't find the reason for this issue though but here is a small workaround:
Update the below layouts and try:
Activity xml :
Added a Framelayout:
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include layout="#layout/content_main"/>
</FrameLayout>
And in MainActivity: Used Framelayout container
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateReportFragment fragment = CreateReportFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(**R.id.container**, fragment, "CreateFragment");
transaction.addToBackStack("CreateBackStack");
transaction.commit();
}
});
In Content.xml Added android:layout_marginTop
<RelativeLayout 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/content_main"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_marginTop="?attr/actionBarSize"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
tools:showIn="#layout/activity_main">
In fragment_create_report.xml added android:layout_marginTop
<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:layout_marginTop="?attr/actionBarSize"
android:background="#android:color/white">
I'm not sure if you still need help with this. But basically the fragment and the activity have to be in different layouts.
This is the general structure for it: (you don't have to use the specific layouts I user below)
<RelativeLayout>
<LinearLayout id="#+id/all_code_relevant_to_activity"></LinearLayout>
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
</LinearLayout>
</RelativeLayout>
Basically you want to have your fragment separate from the rest of the code. So basically you could make a <FrameLayout> around your code in Activity.xml and then add your fragment layout by itself inside the <FrameLayout> but outside <android.support.design.widget.CoordinatorLayout>. Or make two sub layouts the split them apart
It's so wired to show only SUBMIT button on the top of page. I want to suggest you to add fragment instead of replace. please let me know the result after this.
FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_main, fragment, "SearchFragment");
fragmentTransaction.addToBackStack("SearchFragment");
fragmentTransaction.commitAllowingStateLoss();
In your activity xml, add one more element, FrameLayout to host the fragment, like below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/content_main"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="32dp"
android:fontFamily="cursive"
android:text="#string/todd_syndrome" />
<!-- <android.support.design.widget.TextInputLayout
android:id="#+id/layout_last_name"
android:layout_below="#id/headline"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/lastNameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint" />
</android.support.design.widget.TextInputLayout>-->
<EditText
android:id="#+id/editText"
android:layout_below="#id/headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint"/>
<Button
android:id="#+id/submitButton"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:layout_below="#id/editText"
android:onClick="viewPatientReport"/>
<!-- new layout to host fragment -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_holder"/>
</RelativeLayout>
and add your Fragment to that FrameLayout using.
set button property android:translationZ="-3dp" it will work.
What helped me is to add android:translationZ="10dp" to the layout that above the Buttons
I have written a simple application for navigation Drawer based on this tutorial: https://www.youtube.com/watch?v=tZ2DNC3FIic
but there is a problem when I run the application.
The Error is i am having a blank or Empty Drawer List when i launch the application, and instead of that i Got the list in the application launch.
like this image:
This is the main_activity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
tools:context="com.subhi.tabhost.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/main_content"
android:layout_height="match_parent"></RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/drawer_pane"
android:layout_gravity="start"
android:background="#FF4081"
android:layout_height="match_parent"></RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/profile_box"
android:padding="8dp"
android:gravity="center_vertical"
android:layout_height="100dp">
<ImageView
android:id="#+id/icon"
android:layout_margin="5dp"
android:layout_width="50dp"
android:background="#drawable/ic_launcher"
android:layout_height="50dp" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_toRightOf="#+id/icon"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:text="Subhi"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:text="Subhi"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:id="#+id/nav_list"
android:layout_below="#id/profile_box"
android:choiceMode="singleChoice"
android:background="#ffffff"
android:layout_height="match_parent"></ListView>
</android.support.v4.widget.DrawerLayout>
and this is the MainActivity class:
package com.subhi.tabhost;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
RelativeLayout drawerPane;
ListView lvNav;
List<NavItem> listNavItems;
List<Fragment> listFragments;
ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
drawerPane= (RelativeLayout) findViewById(R.id.drawer_pane);
lvNav =(ListView)findViewById(R.id.nav_list);
listNavItems=new ArrayList<NavItem>();
listNavItems.add(new NavItem("sHome", "HomePage", R.drawable.ic_launcher));
listNavItems.add(new NavItem("Setting", "HomePage", R.drawable.ic_launcher));
listNavItems.add(new NavItem("Setting", "HomePage", R.drawable.ic_launcher));
NavListAdapter navListAdapter=new NavListAdapter(getApplicationContext(),R.id.nav_list,listNavItems);
lvNav.setAdapter(navListAdapter);
listFragments=new ArrayList<Fragment>();
listFragments.add(new MyHome());
listFragments.add(new MySettings());
listFragments.add(new MyAbout());
FragmentManager fragmentManager=getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content,listFragments.get(0)).commit();
setTitle(listNavItems.get(0).getTitle());
lvNav.setItemChecked(0, true);
drawerLayout.closeDrawer(drawerPane);
lvNav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, listFragments.get(position)).commit();
setTitle(listNavItems.get(position).getTitle());
lvNav.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerPane);
}
});
actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.drawer_opened,R.string.drawer_closed){
#Override
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
invalidateOptionsMenu();
super.onDrawerClosed(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
and this is the Navlist Adapter Class:
package com.subhi.tabhost;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by subhi on 2/9/2016.
*/
public class NavListAdapter extends ArrayAdapter<NavItem> {
Context context;
int reslayout;
List<NavItem> listNavItem;
public NavListAdapter(Context context, int reslayout, List<NavItem> listNavItem) {
super(context, reslayout, listNavItem);
this.context=context;
this.reslayout=reslayout;
this.listNavItem=listNavItem;
}
#SuppressLint("ViewHolder") #Override
public View getView(int position, View convertView, ViewGroup parent) {
View v=View.inflate(context, reslayout, null);
TextView tvtitle= (TextView) v.findViewById(R.id.titlemain);
TextView tvsubtitle=(TextView)v.findViewById(R.id.subtitle);
ImageView navicon= (ImageView) v.findViewById(R.id.nav_icon);
NavItem navItem=listNavItem.get(position);
tvtitle.setText(navItem.getTitle());
tvsubtitle.setText(navItem.getSubtitle());
navicon.setImageResource(navItem.getResicon());
return v;
}
}
and this is the NavItem Class:
package com.subhi.tabhost;
/**
* Created by subhi on 2/9/2016.
*/
public class NavItem {
private String title;
private String subtitle;
private int resicon;
public NavItem(String title,String subtitle, int resicon ) {
this.subtitle = subtitle;
this.resicon = resicon;
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public int getResicon() {
return resicon;
}
public void setResicon(int resicon) {
this.resicon = resicon;
}
}
and this is one of the Fragments that i used when the item is clicked:
package com.subhi.tabhost;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by subhi on 2/9/2016.
*/
public class MyHome extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_home,container,false);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
and this is the item_nav_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="match_parent">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/ic_launcher"
android:id="#+id/nav_icon" />
<LinearLayout
android:layout_width="wrap_content"
android:orientation="vertical"
android:gravity="center_vertical"
android:layout_margin="10dp"
android:layout_height="40dp">
<TextView
android:layout_width="wrap_content"
android:id="#+id/titlemain"
android:textStyle="bold"
android:textSize="18sp"
android:text="Titile"
android:textColor="#000"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:text="title2"
android:textSize="18sp"
android:id="#+id/subtitle"
android:textColor="#000"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
The error is from this line
new NavListAdapter(getApplicationContext(),R.id.nav_list,listNavItems)
The parameter that you have for R.id.nav_list should be a R.layout.nav_item where nav_item.xml is the layout for a row in the NavListAdapter.
Here
NavListAdapter navListAdapter=new NavListAdapter(getApplicationContext(),R.id.nav_list,listNavItems);
you pass R.id.nav_list which then you want to inflate with
View v=View.inflate(context, reslayout, null);
reslayout cannot be R.id, it has to be layout file (R.layout).
EDIT
Now your main_layout is wrong. Should be like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
tools:context="com.subhi.tabhost.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/main_content"
android:layout_height="match_parent"></RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/drawer_pane"
android:layout_gravity="start"
android:background="#FF4081"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/profile_box"
android:padding="8dp"
android:gravity="center_vertical"
android:layout_height="100dp">
<ImageView
android:id="#+id/icon"
android:layout_margin="5dp"
android:layout_width="50dp"
android:background="#drawable/ic_launcher"
android:layout_height="50dp" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_toRightOf="#+id/icon"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:text="Subhi"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:text="Subhi"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:id="#+id/nav_list"
android:layout_below="#id/profile_box"
android:choiceMode="singleChoice"
android:background="#ffffff"
android:layout_height="match_parent"></ListView>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Hi i'm new to android development i need to show to fragment views in one activity. i need to show this activity immediately after launching app. Please find the attached screen. For your reference, i have added my both XML layouts below :
XML - 1
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:fillViewport="true"
android:scrollbars="none" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/grey_dark"
android:gravity="center"
android:padding="15dp"
android:text="Day One"
android:textColor="#color/white"
android:textSize="16sp"
android:typeface="monospace" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey_line_border" />
<RelativeLayout
android:id="#+id/rlQuestion1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingTop="5dp" >
<TextView
android:id="#+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center"
android:text="09:00 - 09:15"
android:textColor="#drawable/list_text_top_color"
android:textSize="12sp"
android:textStyle="bold"
android:typeface="monospace" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/time"
android:gravity="center"
android:maxLines="2"
android:padding="2dp"
android:text="Introduction & Briefing"
android:textAllCaps="true"
android:textColor="#drawable/list_text_color"
android:textSize="16sp"
android:typeface="monospace" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
XML - 2
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:fillViewport="true"
android:scrollbars="none" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/grey_dark"
android:text="Thank you for attending this event.Kindly take a few minutes to share your feedback with us.Please fill in your contact details clearly or attach your business card.Kindly submit this form at the end of the event."
android:textColor="#color/white"
android:textSize="12sp"
android:typeface="monospace" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey_line_border" />
<com.andreabaccega.widget.FormEditText
android:id="#+id/etUserId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/transparent"
android:ems="10"
android:hint="Name(Mr/Ms/Mdm/Dr)"
android:inputType="text"
android:padding="12dp"
android:textColor="#color/blue"
android:textColorHint="#color/grey_dark"
android:textSize="16sp"
android:typeface="monospace" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey_line_border" />
<com.andreabaccega.widget.FormEditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/transparent"
android:ems="10"
android:hint="Company"
android:inputType="text"
android:padding="12dp"
android:textColor="#color/blue"
android:textColorHint="#color/grey_dark"
android:textSize="16sp"
android:typeface="monospace" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey_line_border" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
here is my code of main activity that i have tried :
package com.pmg.eventapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.pmg.eventapp.R;
import com.viewpagerindicator.TabPageIndicator;
public class MainActivity extends SherlockFragmentActivity {
private static final String[] CONTENT = new String[] { " AGENDA ",
" FEEDBACK " };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_main);
FragmentPagerAdapter adapter = new GoogleMusicAdapter(
getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(pager);
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; finish activity to go home
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
// Set title
getSupportActionBar().setTitle("EVENT APP");
}
class GoogleMusicAdapter extends FragmentPagerAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Voting
return new AgendaFragment();
case 1:
// QA
return new FeedbackFragment();
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toString();
}
#Override
public int getCount() {
return CONTENT.length;
}
}
}
Please help me to create remaining two fragments.Thanks!
This is container where your fragment will be shown : main_container_activity
<LinearLayout 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/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<com.astuetz.viewpager.extensions.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#drawable/background_tab" />
<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="wrap_content"
android:layout_below="#+id/tabs" />
</RelativeLayout>
</LinearLayout>
lets say it is fragment : fragment_activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressBar_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
here is your Container which contains two fragment lets say : MainContainer
public class MainContainer extends SherlockFragmentActivity{
private PagerSlidingTabStrip tabs;
ViewPager mViewPager;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
public static double screenInches;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.main_container_activity);
tabs = (PagerSlidingTabStrip)findViewById(R.id.tabs);
tabs.setIndicatorColorResource(R.color.color_website);
tabs.setShouldExpand(true);
mViewPager = (ViewPager)findViewById(R.id.pager);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager(), MainContainer.this);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
tabs.setViewPager(mViewPager);
mViewPager.setOffscreenPageLimit(1);
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
Context privatecontext;
public AppSectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
privatecontext = context;
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
Fragment fragment = new FragmentActivity();
return fragment;
case 1:
Fragment fragment1 = new FragmentTagsActivity();
return fragment1;
default:
return new FragmentActivity();
}
}
#Override
public int getCount() {
return 2;
}
public CharSequence getPageTitle(int position) {
String name = null;
if (position==0) {
name = privatecontext.getString(R.string.main_tab1);
} else if (position==1) {
name = privatecontext.getString(R.string.main_tab2);
}
return name;
}
}
}
FragmentActivity.java
public class FragmentTagsActivity extends SherlockFragment {
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activity, container, false);
return rootView;
}
}