Startactivity in navigation drawer - java

When we want to change Activity we can use:
Intent i = new Intent(this، ActivityTwo.class);‎
startActivity(i);
When i use it in some Activity it work correctly
But it dose not work when I use it in navigation drawer project. I think it dose not work beacuse Test class extends Fragment. in AppCompatActivity it work.
public class Test extends Fragment {
public Test() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_test , container, false);
button= (Button) v.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent((getActivity(), ActivityTwo.class);‎
startActivity(i);
}
});
return v;
}
}
In my MainActivity I change code:
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment=null;
if (id == R.id.nav_camera) {
Test contactUsFragment=new Test();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.mainLayout,contactUsFragment).commit();
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
ActivityTwoss=new ActivityTwo();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.mainLayout,ss).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

You create a xml container? If so, use a Fragment, not an Activity, for the FragmentManager
In my MainActivity I change code:
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment=null;
if (id == R.id.nav_camera) {
Test contactUsFragment=new Test();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.mainLayout,contactUsFragment).commit();
} else if (id == R.id.nav_gallery) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.fragment_conteiner, new Test(), "Test");
transaction.commit();
} else if (id == R.id.nav_slideshow) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
MainActivity xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="br.com.onuse.finds.Activity.MainActivity"
tools:showIn="#layout/fragment_conteiner"
android:id="#+id/fragment_conteiner">
</FrameLayout>

I think you want to start a new Activity from your Fragment using the following sentence:
Intent i = new Intent((getActivity(), ActivityTwo.class);‎
startActivity(i);
Well, that won't work. You should start your Activity from your current activity (not from your Fragment). You may use something like this:
Intent i = new Intent((getActivity(), ActivityTwo.class);‎
getActivity().startActivity(i);
Or you can do that in one line from your Fragment:
getActivity().startActivity(new Intent(getActivity(), ActivityTwo.class));
Let me know if that works for you!

Related

Unable to handle back button in navigation fragment

In my app I am using a navigation drawer to go different fragment. But when I clicked back button it exit from app. I want when back button clicked in any fragment it navigate to home fragment.
drawer_activity.java to navigate different fragment
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home) {
toolbar.setTitle("HOME");
fragment = new HomeFragment();
} else if (id == R.id.wishlist) {
toolbar.setTitle("YOUR WISHLIST");
} else if (id == R.id.order) {
toolbar.setTitle("YOUR ORDER HISTORY");
} else if (id == R.id.cart) {
toolbar.setTitle("YOUR CART");
} else if (id == R.id.nav_share) {
toolbar.setTitle("HOME");
} else if (id == R.id.account) {
toolbar.setTitle("YOUR ACCOUNT");
} else if (id == R.id.logout) {
finish();
SharedPrefManager.getInstance(getApplicationContext()).logout();
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
homefragment.java
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_home, container,false);
//getting the recyclerview from xml
recyclerView = (RecyclerView) rootView.findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
categoryList = new ArrayList<>();
loadCategory();
customCategoryList = new CustomCategoryList(getActivity(),categoryList);
recyclerView.setAdapter(customCategoryList);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
int id = categoryList.get(position).getCategoryid();
String category = categoryList.get(position).getCategoryname();
final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
ID.setCategoryid(id);
ID.setCategory(category);
Log.e("categoryid",ID.getCategoryid()+"");
Fragment fragment = new ProductListFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content, fragment);
ft.commit();
}
#Override
public void onLongClick(View view, int position) {
}
}));
return rootView;
}
In this fragment when one item click from recycler view it navigate to another fragment. From that fragment when I click back button of my phone it exit from app. I want when back button clicked It goes home fragment always and only back button click from home fragment app exit.
productlistFragment.java
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_product_list, container,false);
gridView = (GridView) rootView.findViewById(R.id.productlist);
category = (TextView) rootView.findViewById(R.id.category);
final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
categoryid = ID.getCategoryid();
category.setText(ID.getCategory());
productList = new ArrayList<>();
loadProduct();
customProductList = new CustomProductList(getActivity(),productList);
gridView.setAdapter(customProductList);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productid = productList.get(position).getProductid();
final GlobalVariable Id = (GlobalVariable)getActivity().getApplication();
Id.setProductid(productid);
Intent intent = new Intent(getActivity(), ProductView.class);
startActivity(intent);
}
});
return rootView;
}
content.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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".DrawerActivity"
tools:showIn="#layout/app_bar_drawer">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
Ok!! Just copy this code and paste you will get what yout want.ft.addToBackStack(null); is the key here.
Fragment fragment = new ProductListFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.content, fragment);
ft.commit();

How change a textview from a fragment on android studio

I am having a problem. I have an activity that implements several fragments. Now I need to update a textview of one of the fragments, I have the string in the activity, so I need to pass this string to the fragment and update that textview.
NavigationDrawer.java --> this is the activity
String user = "";
InicialPage inicialpage = new InicialPage();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_naviagation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
user = extras.getString("KEY"); // TODO this is the value that i need to pass to the fragment InicialPage
}
Bundle bundle = new Bundle();
bundle.putString("USER", user);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
android.support.v4.app.FragmentTransaction fragmenttransaction =
getSupportFragmentManager().beginTransaction();
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
//inicialpage.setUsernameTextView(user);
DrawerLayout drawer1 = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer1.closeDrawer(GravityCompat.START);
TextView userNameTextView = (TextView)findViewById(R.id.usernametext);
//userNameTextView.setText(user);
android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.InicialPage);
}
#Override
public void onBackPressed () {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.naviagation_drawer, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected (MenuItem item){
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.FragmentTransaction fragmenttransaction =
getSupportFragmentManager().beginTransaction();
if (id == R.id.InicialPage) {
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
} else if (id == R.id.HistoryItem) {
fragmenttransaction.replace(R.id.container, new Historic());
fragmenttransaction.commit();
} else if (id == R.id.FriendsItem) {
fragmenttransaction.replace(R.id.container, new Friends());
fragmenttransaction.commit();
} else if (id == R.id.PointsItem) {
fragmenttransaction.replace(R.id.container, new Points());
fragmenttransaction.commit();
} else if (id == R.id.BookBikeItem) {
fragmenttransaction.replace(R.id.container, new BookBike());
fragmenttransaction.commit();
} else if (id == R.id.MessagesItem) {
fragmenttransaction.replace(R.id.container, new Messages());
fragmenttransaction.commit();
}else if(id == R.id.Mapdebug)
{
Intent maps = new Intent(this,MapsActivity.class);
startActivity(maps);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void FrameClicked(View view) {
//send user name to chat
Intent i = new Intent(this, Chat.class);
i.putExtra("USER", user);
startActivity(i);
}
public void addFriend(View view) {
LinearLayout principalLayout= (LinearLayout) findViewById(R.id.idFriendsVertical);
LinearLayout secondaryLauout= new LinearLayout(this);
TextView tx= new TextView(this);
EditText et= (EditText) findViewById(R.id.ADD);
String edittx= String.valueOf(et.getText().toString());
if (edittx.equals("")) {
}else
{
tx.setText(edittx);
tx.setTextSize(22);
tx.setTextColor(Color.BLACK);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.setMargins(0, 20, 0, 10);
secondaryLauout.addView(tx, params);
principalLayout.addView(secondaryLauout);
}
et.setText("");
}
}
InicialPage.java --> this is the fragment
public class InicialPage extends Fragment {
SQLiteDatabase db;
View view;
TextView usernameTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_inicial_page, container, false);
usernameTextView = (TextView) view.findViewById(R.id.usernametext);
return view;
}
If I understand your question correctly, you need to add inicialpage.setArguments(bundle); before your replace and commit in your fragment transaction.
Then, inside your Fragment you call
Bundle bundle = getArguments();
String bundleText = bundle.getString("USER");
to retrieve it.
You were already creating a bundle so I'm assuming that's the data you want to send. You have to attach that bundle to the Fragment before your Fragment Transaction though.
Inside your Activity:
Bundle bundle = new Bundle(); //create the bundle
bundle.putString("USER", user); //attach data to the bundle
inicialpage.setArguments(bundle); //set the bundle on the fragment
//perform fragment transaction
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
Inside your Fragment:
//retrieve the bundle
Bundle bundle = getArguments(); //retrieve the bundle
String bundleText = bundle.getString("USER"); //get the data on the bundle
//find view & set the text
usernameTextView = (TextView) view.findViewById(R.id.usernametext);
usernameTextView.setText(bundleText);
This type of problem can be solved using Localbroadcast Receiver .Write the following code in your fragment. Something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("custom-event-name"));
return view;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
usernameTextView.setText(message);
Log.d("receiver", "Got message: " + message);
}
};
then pass the user value by adding this following code in your activity when you want to pass
Intent intent = new Intent("custom-event-name");
intent.putExtra("message", user);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

want to use setvisibily method betwen two framelayout in android

I am trying to use two framelayouts to load the content. My problem is both pages are showing data at the same time. I want to use setVisibilty method in the main java file. When one frame is showing data the other frame hides automatically. Could anyone tell me the java codes. Here is the xml file:
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<FrameLayout
android:id="#+id/content_frametwo"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
I am giving you the java file here:-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void setFrameVisibility(boolean frameOneVisible){
if (frameOneVisible){
findViewById(R.id.content_frame).setVisibility(View.VISIBLE);
findViewById(R.id.content_frametwo).setVisibility(View.GONE);
} else {
findViewById(R.id.content_frame).setVisibility(View.GONE);
findViewById(R.id.content_frametwo).setVisibility(View.VISIBLE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.homepage) {
Intent homepage = new Intent (MainActivity.this, MainActivity.class);
startActivity(homepage);
// Handle the camera action
} else if (id == R.id.foodpage) {
//handle the food page here
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.schedulepage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ScheduleFragment())
.commit();
} else if (id == R.id.emotionspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new EmotionsFragment())
.commit();
} else if (id == R.id.basicneedspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frametwo
, new BasicneedsFragment())
.commit();
} else if (id == R.id.exit) {
askBeforeExit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onBackPressed() {
askBeforeExit();
}
private void askBeforeExit(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Confirm Exit");
builder.setMessage("Are you sure you want to quit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
}
You could make a function to set them both, but then you will have to make sure you always use that function:
private void setFrameVisibility(boolean frameOneVisible) {
if (frameOneVisible) {
findViewById(R.id.content_frame).setVisibility(View.VISIBLE);
findViewById(R.id.content_frametwo).setVisibility(View.GONE);
} else {
findViewById(R.id.content_frame).setVisibility(View.GONE);
findViewById(R.id.content_frametwo).setVisibility(View.VISIBLE);
}
}
You can implement this by using this code:
inside onCreateView:
frameLayout1 = (FrameLayout) findViewById(R.id.frameLayout1);
frameLayout2 = (FrameLayout) findViewById(R.id.frameLayout2);
When ever you want to change visibility:
frameLayout1.setVisibility(View.VISIBLE);
frameLayout2.setVisibility(View.GONE);

java.lang.IllegalArgumentException: DrawerLayout must be measured with MeasureSpec.EXACTLY

I searched a lot of questions , but none of the answers helped me ! I connected an activity with a navigation drawer to a fragment ... but I start from this mistake ! Thanks for your help!
java.lang.IllegalArgumentException: DrawerLayout must be measured with MeasureSpec.EXACTLY.
xml class
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="#color/colorAccent">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
/>
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:paddingTop="80dp"/>
</android.support.v4.widget.DrawerLayout>
hedline fragment
public class HeadlinesFragment extends ListFragment {
String[] Headlines = {
"Article One",
"Article Two",
"Article 3",
"Article 4",
"Article 5",
"Article 6",
};
SearchView search_view;
OnHeadlineSelectedListener mCallback;
String[] menutitles;
TypedArray menuIcons;
CustomAdapter adapter;
private List<RowItem> rowItems;
// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onArticleSelected(int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// We need to use a different list item layout for devices older than Honeycomb
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
return inflater.inflate(R.layout.list_fragment, null, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1));
rowItems.add(items);
}
adapter = new CustomAdapter(getActivity(), rowItems);
setListAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
// When in two-pane layout, set the listview to highlight the selected list item
// (We do this during onStart because at the point the listview is available.)
if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
mCallback.onArticleSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
}
main activity of fragment`
public class MainActivity_list extends FragmentActivity
implements HeadlinesFragment.OnHeadlineSelectedListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
HeadlinesFragment firstFragment = new HeadlinesFragment();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Capture the article fragment from the activity layout
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// If the frag is not available, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
article fragment.java
public class ArticleFragment extends Fragment {
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// If activity recreated (such as from screen rotate), restore
// the previous article selection set by onSaveInstanceState().
// This is primarily necessary when in the two-pane layout.
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_main, container, false);
}
#Override
public void onStart() {
super.onStart();
// During startup, check if there are arguments passed to the fragment.
// onStart is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method
// below that sets the article text.
Bundle args = getArguments();
if (args != null) {
// Set article based on argument passed in
updateArticleView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
// Set article based on saved instance state defined during onCreateView
updateArticleView(mCurrentPosition);
}
}
public void updateArticleView(int position) {
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current article selection in case we need to recreate the fragment
outState.putInt(ARG_POSITION, mCurrentPosition);
}
}
mainactivity.java (of navgation drawer)
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String[] lista = {
"Article One",
"Article Two",
"Article 3",
"Article 4",
"Article 5",
"Article 6",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#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.btnMyMenu) {
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
drawer.openDrawer(Gravity.RIGHT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
};
drawer.setDrawerListener(toggle);
toggle.syncState();
Button btn=(Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
drawer.openDrawer(Gravity.RIGHT);
}
}
});
ListView lv = (ListView) findViewById(R.id.drawer_list);
// Convert ArrayList to array
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_menu,R.id.menu_text, lista));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent activity0 = new Intent(MainActivity.this, pagina1.class);
startActivity(activity0);
break;
case 1:
Intent activity1 = new Intent(MainActivity.this, pagina1.class);
startActivity(activity1);
break;
}
}
#SuppressWarnings("unused")
public void onClick(View v) {
}
;
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
int menuToUse = R.menu.my_right_side_menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(menuToUse, menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(Gravity.RIGHT);
return true;
}
}
there is also a rowitem.java, customadapeter.java
app_bar.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.chiari.nicola.myapplication.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.CoordinatorLayout>
content_main.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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.chiari.nicola.myapplication.MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"/>
</RelativeLayout>
As the Error say: Change the DrawerLayout width to some definite value like 240dp instead of match_parent
See the source Code:
if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
if (isInEditMode()) {
// Don't crash the layout editor. Consume all of the space if specified
// or pick a magic number from thin air otherwise.
// TODO Better communication with tools of this bogus state.
// It will crash on a real device.
if (widthMode == MeasureSpec.AT_MOST) {
widthMode = MeasureSpec.EXACTLY;
} else if (widthMode == MeasureSpec.UNSPECIFIED) {
widthMode = MeasureSpec.EXACTLY;
widthSize = 300;
}
if (heightMode == MeasureSpec.AT_MOST) {
heightMode = MeasureSpec.EXACTLY;
}
else if (heightMode == MeasureSpec.UNSPECIFIED) {
heightMode = MeasureSpec.EXACTLY;
heightSize = 300;
}
} else {
throw new IllegalArgumentException(
"DrawerLayout must be measured with MeasureSpec.EXACTLY.");
}
}
I had a similar issue, during investigation I discovered that it was because HorizontalScrollVIew was in my view hierarchy, try to play with that

Android app using OnClickListener closes on startActivity(intent)

I have an OnClickListener in a fragment activity as shown here:
public class Menu1_Fragment extends Fragment {
Button CreateGroupButton;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
CreateGroupButton = (Button) rootview.findViewById(R.id.create_study_group);
CreateGroupButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(getActivity().getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Menu1_Fragment.this.getActivity(), CreateGroup.class);
startActivity(intent);
}
});
return rootview;
}
}
Here is my menu1_layout.xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<Button
android:id="#+id/create_study_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/CreateGroupBtn"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is the page where you can create and view existing groups"
android:id="#+id/textView"
android:layout_below="#+id/create_study_group"/>
</RelativeLayout>
When the Button is clicked, the "Test" message is displayed but the app closes right after.
Here is the CreateGroup java class:
public class CreateGroup extends Fragment{
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.create_group, container, false);
return rootview;
}
}
and the create_group.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is the page where the form is displayed"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
NavigationActivity:
public class NavigationActivity extends FragmentActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
FragmentManager fragmentManager = getSupportFragmentManager();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager =getSupportFragmentManager();
Fragment fragment= new Fragment();
switch (position){
case 0:
mTitle = getString(R.string.title_section1);
fragment = new Menu1_Fragment();
break;
case 1:
mTitle = getString(R.string.title_section2);
fragment = new Menu2_Fragment();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.navigation, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//if the log out button is selected, log out of Parse and go back to log in page
if (id == R.id.action_logout) {
ParseUser.logOut();
Intent intent = new Intent(NavigationActivity.this,LoginSignupActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Successfully Logged out", Toast.LENGTH_LONG).show();
finish();
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((NavigationActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
I'm having trouble figuring out why the CreateGroup class/layout file aren't being displayed as a new page.
The CreateGroup class is a fragment , the intent should be using an activity if startActivity is being used
CreateGroup is a fragment, so you should change fragments and not start an activity:
CreateGroupButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Toast.makeText(getActivity().getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
// Create new fragment and transaction
Fragment createGroupFragment = new CreateGroup();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, createGroupFragment)
.commit();
}
});

Categories

Resources