iam new to android and iam trying to create an app with a lot of websites linked on to the apps like facebook, twitter , mail etc
MainActivity.java
package com.shortshop.app;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
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 android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new ThreeFragment(), "THREE");
adapter.addFrag(new FourFragment(), "FOUR");
adapter.addFrag(new FiveFragment(), "FIVE");
adapter.addFrag(new SixFragment(), "SIX");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
OneFragment.java
package com.shortshop.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
fragment_one.xml
<ScrollView xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableRow>
<ImageButton
android:id="#+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_weight="2"
android:onClick="facebook"
android:src="#drawable/facebook_icon" />
</TableRow>
</TableLayout>
</ScrollView>
Iam not able to add this code in the OneFragment.java where i endup with error
public class OneFragment extends Fragment {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_one);
}
public void facebook(View v){
Intent intent = new Intent(this, WebActivity.class);
startActivity(intent);
}
}
It would be great full if some comes out with a solution i have been trying to figure out the solution for so long
WebActivity.java
package com.shortshop.app;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class WebActivity extends Activity {
private WebView mWebview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
mWebview .loadUrl("http://www.facebook.com");
setContentView(mWebview );
}
}
activity_web.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.shortshop.app.WebActivity">
<WebView
android:layout_width="368dp"
android:layout_height="495dp"
android:id="#+id/webView"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</android.support.constraint.ConstraintLayout>
In your OneFragment.java. post this code.
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
ImageButton imageButton= (ImageButton ) view.findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, WebActivity.class);
startActivity(intent);
}
});
return view;
}
}
Related
I'm fairly new to android studio so I will try to explain as best as I can.
I've made a menu using fragments, so my activity_home is a fragmented activity. Inside the fragmented activity I've created a button that, upon clicking, should open a new activity.
The problem is that I don't know how to implement the onClickListener inside the fragmented activity.
Every tutorial I went trough does it from the beginning.
This is my main activity:
package com.example.relja.diplomskirad;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
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 android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new home(), "Home");
adapter.addFragment(new profil(), "Profil");
adapter.addFragment(new mapa(), "Mapa");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(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);
}
}
}
This is my 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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
This is home.java where i want to put the onclick listener:
package com.example.relja.diplomskirad;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class home extends Fragment {
public home() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_home, container, false);
}
}
And this is home xml where the button is:
<?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"
tools:context=".home">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:orientation="vertical">
<LinearLayout
android:id="#+id/glavnaStranica1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal"
android:gravity="center">
<ImageView
android:id="#+id/logoSlika"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/logo2"
android:layout_gravity="center"/>
</LinearLayout>
<LinearLayout
android:id="#+id/glavnaStranica2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginStart="30dp">
<EditText
android:id="#+id/search"
android:layout_width="250dp"
android:layout_height="38dp"
android:hint="#string/search"
android:background="#drawable/ivica"
android:drawableLeft="#drawable/search"
android:drawablePadding="10dp"
android:inputType="text"
/>
<Button
android:id="#+id/dugme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dugme"
/>
</LinearLayout>
<Button
android:id="#+id/dugmeLogin"
android:layout_width="70dp"
android:layout_height="40dp"
android:text="#string/dugmeLogin"
android:layout_gravity="end"
android:layout_marginRight="10dp"
android:onClick="loginLogin"
style="?android:attr/borderlessButtonStyle"/>
</LinearLayout>
</RelativeLayout>
You can try this.. this will help
public class home extends Fragment {
private Button btn_dumge_login;
public home() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btn_dumge_login = view.findViewById(R.id.dumgeLogin)
btn_dumge_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), TestActivity.class) ;
getActivity().startActivity(intent);
}
});
}
}
View view = inflater.inflate(R.layout.your_layout_file, container, false);
view.findViewById(R.id.button_id).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
getContext().startActivity(new Intent(getContext(), YourNewActivity.class));
});
return view;
you can use this code in your fragment 'home' in onCreateView() method
You should select first the view you want to be navigated from, for example, the Button with id dugmeLogin
then your code should be something like that
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_home, container, false);
Button loginButton = view.findViewById(R.id.dugmeLogin);
loginButton.setOnClickListener(v -> {
// You code goes here
});
return view;
}
this is in your home.java
I want to pass some List from fragment into 2 other fragment. When i pass data to fragment two it is going well. But it is error when pass to the fragment three
Error code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yehezkiel.eclassapp, PID: 15267
java.lang.IllegalArgumentException: No view found for id 0x7f0d00c4 (com.example.yehezkiel.eclassapp:id/fragment3) for
fragment ThreeFragment{e045027 #3 id=0x7f0d00c4}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1415)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1752)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1821)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2595)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2382)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2337)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2244)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:702)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
Pass Code in OneFragment.java
Bundle bundle=new Bundle();
bundle.putStringArrayList("keys", keys);
//set Fragmentclass Arguments
Fragment fragobj=new TwoFragment();
fragobj.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frag2, fragobj).commitAllowingStateLoss();
Bundle bundle2=new Bundle();
bundle2.putStringArrayList("keys", keys);
//set Fragmentclass Arguments
Fragment fragobj2=new ThreeFragment();
fragobj2.setArguments(bundle2);
FragmentManager fragmentManager2 = getFragmentManager();
fragmentManager2.beginTransaction().replace(R.id.fragment3, fragobj2).commitAllowingStateLoss();
the first pass into TwoFragment did well. But the second pass gave me error like that. Please help me. I have been check all of the id in the ThreeFragment.xml and all correct.
ThreeFragment.java
package com.example.yehezkiel.eclassapp;
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 java.util.ArrayList;
import java.util.List;
public class ThreeFragment extends Fragment {
View v;
private List<DaftarPengumuman> listPengumuman = new ArrayList<>();
private ArrayList<String> obj3 = new ArrayList<>();
public ThreeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_three, container, false);
Bundle bundle = this.getArguments();
if(getArguments()!=null)
{
obj3 = bundle.getStringArrayList("keys");
Log.e("nba",obj3.toString());
}
// Inflate the layout for this fragment
return v;
}
}
fragment_three.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment3"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.yehezkiel.eclassapp.ThreeFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</FrameLayout>
This is my MainActivity.java that is stored the viewpager
package com.example.yehezkiel.eclassapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
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 android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<MataKuliah> listMatkul = new ArrayList<>();
private ArrayList<String> keys = new ArrayList<>();
private myAdapter myAdapter;
private Button logoutBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener authListener;
private RecyclerView mRecycleView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private NavigationView mNavigationView;
private TextView mTextName;
private TextView mTextNim;
private ProgressBar mProgressBar;
static {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
FirebaseUser users = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mataKuliahRef = FirebaseDatabase.getInstance().getReference("courses");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mAuth = FirebaseAuth.getInstance();
//Navbar menu
mToolbar = (Toolbar) findViewById(R.id.navbaraction);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawabel_main);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
View header = mNavigationView.getHeaderView(0);
mTextName = (TextView) header.findViewById(R.id.header_name);
mTextNim = (TextView) header.findViewById(R.id.header_nim);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar2);
mProgressBar.setVisibility(View.VISIBLE);
//Tab Layout
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case (R.id.tugas):
break;
case (R.id.logout_menu):
signOut();
break;
}
return true;
}
});
userRef.child(users.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("name").getValue().toString();
String nim = (String) dataSnapshot.child("nim").getValue().toString();
mTextNim.setText(nim);
mTextName.setText(name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Beranda");
adapter.addFragment(new TwoFragment(), "Tugas");
adapter.addFragment(new ThreeFragment(), "Pengumuman");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(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);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void signOut() {
mAuth.signOut();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(authListener);
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawabel_main"
tools:context="com.example.yehezkiel.eclassapp.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
layout="#layout/navbar_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"></include>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<ProgressBar
android:id="#+id/progressBar2"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:visibility="visible"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="304dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/MainRView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginEnd="6dp"
android:layout_marginStart="6dp"
android:layout_marginTop="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/logoutBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="444dp"
android:background="#color/colorPrimary"
android:text="LOGOUT"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.945"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navbar_main"
android:layout_gravity="start"
app:headerLayout="#layout/navbar_header"
android:id="#+id/nav_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Problem Statement:
I have an activity on which I have used a view pager and inflated two fragments inside it.
The second fragment inside the view pager must also contain a view pager which has another fragment inside it(If you're wondering why this is a view pager if only a single fragment is required, because that is a configurable component and more fragments might be required inside it).
First Fragment
Second Fragment and the sub fragment inside it
Now, when we click a button I have to refresh the first and second fragments as well as the sub fragment( in the ViewPager) inside the second fragment.
The issue is that the first and the second fragments are getting updated but the sub fragment that is inside the view pager in the second fragment is not getting refreshed.
This happens after the click of the button:
First Fragment refreshed
Second fragment refreshed but the sub fragment did not
Tried solutions:
We tried to debug the code, tried clearing the adapters and the lists. Nothing worked.
Any pointers or suggestions welcome !
Code :
MainActivity.java
package com.example.admin.myapplication;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private GuestListPagerAdapter adapter;
private ViewPager viewPager;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
button = findViewById(R.id.button);
setUpViewPager();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.clearFragmentList();
adapter.addFragment(FirstFragment.newInstance("55"));
adapter.addFragment(SecondFragment.newInstance("88"));
adapter.notifyDataSetChanged();
}
});
}
private void setUpViewPager() {
if (null == adapter)
adapter = new GuestListPagerAdapter(getSupportFragmentManager());
adapter.addFragment(FirstFragment.newInstance("1"));
adapter.addFragment(SecondFragment.newInstance("2"));
viewPager.setAdapter(adapter);
}
public class GuestListPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
GuestListPagerAdapter(FragmentManager fm) {
super(fm);
}
void addFragment(Fragment fragment) {
mFragments.add(fragment);
}
void clearFragmentList(){
mFragments.clear();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
activity_main.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:orientation="vertical"
android:weightSum="10"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"/>
<Button
android:text="Refresh View Pager"
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_gravity="center"/>
</LinearLayout>
SecondFragment.java
package com.example.admin.myapplication;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class SecondFragment extends Fragment {
private static final String TAG = SecondFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public SecondFragment() {
// Required empty public constructor
}
public static SecondFragment newInstance(String param1) {
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: 2F");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
Log.d(TAG, "onCreate: 2F");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv2);
tv.setText(mParam1);
ViewPager pager = (ViewPager) view.findViewById(R.id.sub_view_pager);
SubListPagerAdapter adapter = new SubListPagerAdapter(getChildFragmentManager());
adapter.clearFragmentList();
adapter.addFragment(SubFragment.newInstance(mParam1));
pager.setAdapter(adapter);
Log.d(TAG, "onCreateView: 2F");
return view;
}
public class SubListPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
SubListPagerAdapter(FragmentManager fm) {
super(fm);
}
void addFragment(Fragment fragment) {
mFragments.add(fragment);
}
void clearFragmentList(){
mFragments.clear();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
fragment_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="4"
tools:context=".SecondFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/tv2"
android:textSize="60sp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="#string/hello_blank_fragment" />
<android.support.v4.view.ViewPager
android:background="#color/colorAccent"
android:id="#+id/sub_view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"/>
</LinearLayout>
SubFragment.java
package com.example.admin.myapplication;
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.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SubFragment extends Fragment {
private static final String TAG = SubFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public SubFragment() {
// Required empty public constructor
}
public static SubFragment newInstance(String param1) {
SubFragment fragment = new SubFragment();
Bundle args = new Bundle();
if(fragment.getArguments()!=null)
fragment.getArguments().clear();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: sub");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: sub");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sub, container, false);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
TextView tv = (TextView) view.findViewById(R.id.sub_tv);
tv.setText(mParam1);
Log.d(TAG, "onCreateView: sub");
return view;
}
}
fragment_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SubFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/sub_tv"
android:textSize="60dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_blank_fragment" />
</LinearLayout>
FirstFragment.java
package com.example.admin.myapplication;
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.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class FirstFragment extends Fragment {
private static final String TAG = FirstFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public FirstFragment() {
// Required empty public constructor
}
public static FirstFragment newInstance(String param1) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: 1F");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
Log.d(TAG, "onCreate: 1F");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(mParam1);
Log.d(TAG, "onCreateView: 1F");
return view;
}
}
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".FirstFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/tv"
android:textSize="60sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
I have four fragments in my application. the first one gets GPS data for calculating speed which works fine. as soon as the application gets the gps data and move to other fragments it crashes. FYI, other fragments are all without any code.
here is my MainActivity class:
package ir.helpx.speedx;
import android.Manifest;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.WindowManager;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar =(Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new HomeFragment(), "Home");
viewPagerAdapter.addFragments(new CompassFragment(), "Compass");
viewPagerAdapter.addFragments(new HUDFragment(), "HUD");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"GPS permission granted", Toast.LENGTH_LONG).show();
// get Location from your device by some method or code
} else {
// show user that permission was denied. inactive the location based feature or force user to close the app
}
break;
}
}
}
and my MainActivity 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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ir.helpx.speedx.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="368dp"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="8dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="#layout/toolbar_layout"
/>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabLayout"
app:tabMode="fixed"
app:tabGravity="fill"
></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/viewPager"
></android.support.v4.view.ViewPager>
</android.support.design.widget.AppBarLayout>
</android.support.constraint.ConstraintLayout>
and here is my first Fragment called Home:
package ir.helpx.speedx;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment implements LocationListener{
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
LocationManager mgr;
mgr = (LocationManager)getContext().getSystemService(getActivity().LOCATION_SERVICE);
mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
return inflater.inflate(R.layout.fragment_home, container, false);
}
//TextView msg1;
#Override
public void onLocationChanged(Location location) {
if (location==null){
TextView currentSpeed = null;
}
else {
float nCurrentSpeed = location.getSpeed();
TextView currentSpeed = (TextView) getView().findViewById(R.id.speed);
currentSpeed.setText((int)nCurrentSpeed*18/5+"");
//msg1=currentSpeed;
Toast.makeText(getActivity(), "Location Found!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
and here is the related 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="ir.helpx.speedx.HomeFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/speed"
android:gravity="center"
android:textSize="180sp"
android:textStyle="bold"
android:textColor="#android:color/white"
android:id="#+id/speed"/>
</FrameLayout>
and here is my second Fragment:
package ir.helpx.speedx;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class HUDFragment extends Fragment {
public HUDFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_hud, container, false);
}
}
rest of the fragments are similar to
I have a toolbar XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minWidth="?attr/actionBarSize"
android:fitsSystemWindows="true"
android:id="#+id/toolBar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
</android.support.v7.widget.Toolbar>
and finally my my ViewPagerAdapter:
package ir.helpx.speedx;
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 java.util.ArrayList;
/**
* Created by abe on 5/29/2017.
*/
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragments, String titles){
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
Please HELP me! thank you
I think I could fix it by adding
viewPager.setOffscreenPageLimit(4);
to my MainActivity. I think that was because by default ViewPager retains only one page in the view hierarchy in an idle state. Please tell me if I did the right thing!
I am new in android programing. I want to add a facebook login page in my ting an error while adding a fragment in my main activity.
Here is My Fragment Class
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MyFragment extends Fragment {
private OnFragmentInteractionListener mListener;
TextView textView;
private CallbackManager mcallbackManager;
private FacebookCallback<LoginResult> mCallback= new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken= loginResult.getAccessToken();
Profile profile= Profile.getCurrentProfile();
if(profile != null){
textView.setText("Welcome "+ profile.getName());
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MyFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mcallbackManager=CallbackManager.Factory.create();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton=(LoginButton)view.findViewById(R.id.login_button);
loginButton.setReadPermissions("User_Friends");
loginButton.setFragment(this);
loginButton.registerCallback(mcallbackManager, mCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mcallbackManager.onActivityResult(requestCode,resultCode,data);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
Fragment XML Code
<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.mma.androidfacebook3.MyFrgment"
>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="left|top" />
</RelativeLayout>
MainActivity XML Code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:id="#+id/main_layout">
MainActivity class code
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
Fragment.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment myfragment= new MyFragment();
FragmentManager fragmentManager= getFragmentManager();
FragmentTransaction fragmentTransaction= fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.main_layout, myfragment, "dfs");
fragmentTransaction.commit();
}
}
Error
Error:(24, 51) error: incompatible types: MyFragment cannot be converted to Fragment
The minimum sdk viersion for this app is 9 and maximus sdk is 21.
It will be very helpfull if anyone suggest me how to solve this problem.
Thank You.
You need to import
import android.support.v4.app.Fragment
instead of
import android.app.Fragment;
in your MainActivity