want to use setvisibily method betwen two framelayout in android - java

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);

Related

Cant open file.txt from raw folder on a fragment

I'm trying to open file.txt from my raw folder through a fragment.
here is my code on KonsumerFragment.java
public class KonsumerFragment extends Fragment implements View.OnClickListener{
public KonsumerFragment() {
// Required empty public constructor
}
float marginValue;
Spinner spinnerProduct;
Spinner spinnerType;
EditText pengajuan;
EditText tenor;
TextView tvAngsuran;
String[] arrayMargin;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_konsumer, container, false);
//Define Variables
spinnerProduct = (Spinner) v.findViewById(R.id.spinnerProduct) ;
spinnerType = (Spinner) v.findViewById(R.id.spinnerType);
pengajuan = (EditText) v.findViewById(R.id.etPengajuan);
tenor = (EditText) v.findViewById(R.id.etTenor);
// Inflate the layout for this fragment
Button hitung = (Button) v.findViewById(R.id.btnHitung);
hitung.setOnClickListener(this);
return v;
}
#Override
public void onClick(View view) {
try {
switch (view.getId()){
case R.id.btnHitung :
//simulate();
readMargin();
break;
}
} catch (Exception e){
e.getCause();
e.printStackTrace();
}
}
public void readMargin() throws FileNotFoundException {
try {
InputStream in = getContext().getResources().openRawResource(R.raw.margingriyafix);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
String result = "";
while(line !=null){
result += line + "\n";
}
arrayMargin = result.split("\\n");
for (int i=0 ; i<arrayMargin.length ; i++){
System.out.println(arrayMargin[i]);
}
System.out.println(arrayMargin);
} catch (Exception e){
System.out.println(e);
e.getCause();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
KonsumerFragment konsFragment = new KonsumerFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, konsFragment);
transaction.commit();
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);
}
#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.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_konsumer) {
KonsumerFragment konsFragment = new KonsumerFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, konsFragment);
transaction.commit();
} else if (id == R.id.nav_produktif) {
ProduktifFragment prodFragment = new ProduktifFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, prodFragment);
transaction.commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
the part of the reading file has been in the right way. I tested it running on MainAcivity directly. but it won't run on Fragment. it has been successfully running on an Activity, I believe that the problem comes from the InputStream, but anyway I've tried doing like
getActivity().getResources().openRawResource(R.raw.margingriyafix);
and also
getContext().getResources().openRawResource(R.raw.margingriyafix);
still not working.
please anyone help me.

Navigation Icon causes application to close

I am a newbie to Android Studio but have successfully gone quite far, including a successful login screen. But I am getting stuck at a point.
The navigation icon created using ActionBarDrawerToggle works fine on the homescreen. Then on clicking on any of the options, it successfully loads the fragment. But when I click on the the icon again to go to another fragment, the navigation drawer open but the application closes. The debugger shows no error, it only reports that the onStop and onPause events have been triggered (which are empty since I have no use with them).
I have tried a lot but I am unable to find a solution to this problem.
I even attempted to create a custom view on the ActionBar with a custom ImageButton, and I set a click listener. That worked fine, but I want to use the default method, i.e. ActionBarDrawerToggle.
Open to all suggestions!
My HomeAcivity.java, where I am using the alternate I custom-built.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.actionbar, null);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(v);
ImageButton drawer = (ImageButton) findViewById(R.id.btn1);
drawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.home, 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_logout) {
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
SessionManager session = new SessionManager(getApplicationContext());
db.deleteUsers();
session.setLogin(false);
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
startActivity(intent);
finish();
return true;
}else if(id == android.R.id.home){
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
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_profile) {
ProfileFragment profileFragment = new ProfileFragment();
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_home_fragment, profileFragment, profileFragment.getTag()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.profile_heading);
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_cmi) {
} else if (id == R.id.nav_inspire) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

Navigation drawer: how to make the item direct you to a website. Android Studio

Hi guys perfect saturday for some coding :)
I have a navigation drawer where i can click on items and they direct me to fragments. But how i make so when i press an item in the navigation drawer to link me to a website. I'm not really good at items..
I will post three different imgur images See the 3 images here
So when you press it, example: www.google.com comes up in your regular "chrome app" i'm not really interested in webview cause of the website is not html5.
This is my MainActivity at the bottom of it you can find how i use the items for my fragments.
I'm a rookie programmer hehe... But it is so fun! Learning step by step.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//TextView tstnr;
TextView radertst;
Button sendSMSaon;
EditText aonTxt;
//TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
// tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
// nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#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.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) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
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.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You need something like this in your onClick method of a button, or listener, however you wanna handle the click event:
Intent intent = new Intent("android.intent.action.VIEW",
Uri.parse("http://www.google.com/"));
startActivity(intent);
If you don't know how to handle the click itself check this out., but I see in your code that you can, so it's fine.
Just add this on your menu item
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
so on your onNavigationItemSelected you have to add another if and search for the id of the item you need:
I made an example
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
else if (id == R.id.YOUR_ITEM_ID) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}

Image Button Click Event is not working

I had create a small for testing and studying purpose. It consist of an image button and the action is to show a toast while pressing the image button.
I had changed everything but toast message is not showing. There is no single error or warning in the code.
Last day, I posted the code here and didn't get an answer.
So this time I uploaded the Source code. Hope somebody can solve this simple solution.
https://drive.google.com/file/d/0B6Ax58vO7SvZcGRwNFlyYzhqZFk/view?usp=sharing
just remove this code from content and place it in MainActivity.java
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton:
Toast.makeText(getApplicationContext(),"You download is resumed",Toast.LENGTH_LONG).show();
break;
}
}
Rememeber
If you set any onClick event in a layout file (xml), you have to create the method in the parent activity that will use that layout.
this is complete wroking code.
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="switchmode.lteonly.lteonlyswitch.MainActivity"
tools:showIn="#layout/app_bar_main">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:clickable="true"
android:layout_centerVertical="true"
android:layout_centerInParent="true"
android:src="#drawable/myimage"
android:onClick="onClick"/>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
}
#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.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(GravityCompat.START);
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton:
Toast.makeText(getApplicationContext(),"You download is resumed",Toast.LENGTH_LONG).show();
break;
}
}
}
Contentmain.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
ImageButton imgButton =(ImageButton)findViewById(R.id.imageButton);
// imgButton.setOnClickListener(this);
}

Android Fragment Orientation Causes Attach Issues

Hello everyone I have a question on rotating fragments and restoring them after detaching them. Currently I have three fragments: Fragment_Data, Fragment_Log, and Fragment_Control. My problem is if I rotate Fragment_Data, then detach and add Fragment_Log, then detach Fragment_Log and attempt to attach Fragment Data it fails to reattach. If I keep the device vertical and repeat the same steps the fragments don't have any issues reattaching. I try to detach, add, and attach the fragments in my PanelManager method.
What exactly is going one during the lifecycle of the Fragment_Data that causes issues when trying to reattach?
MainActivty.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FragmentControl.ButtonSetListener{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentControlTransction = fragmentManager.beginTransaction();
FragmentTransaction fragmentDataTransaction = fragmentManager.beginTransaction();
FragmentControl fragmentControl = new FragmentControl();
FragmentData fragmentData = new FragmentData();
FragmentLog fragmentLog = new FragmentLog();
FragmentGraph fragmentGraph = new FragmentGraph();
//Create Fragment Manager
FragmentManager panelManager = getFragmentManager();
//Boolean values for panels
boolean data_panel = true; //True because it is the first panel created in the View; id = 1
boolean log_panel = false; //id = 2
boolean graph_panel = false; //id = 3
#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);
// 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;
}
//Generate Fragment_Data and Fragment_Control Panels
//These are the first two panels introduced into the app
fragmentControlTransction.add(R.id.fragment_control_panel, fragmentControl, "control");
fragmentControlTransction.commit();
fragmentDataTransaction.add(R.id.fragment_data_panel, fragmentData, "data");
fragmentDataTransaction.commit();
}
#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.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.data_log) {
PanelManager(2);
} else if (id == R.id.data_graph) {
PanelManager(3);
} else if (id == R.id.nav_share) {
PanelManager(1);
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void PanelManager(int panel_id){
if(panel_id == 1){
//detach any panel attached to the fragment_data_panel
panelManager.beginTransaction().detach(getFragmentManager().findFragmentById(R.id.fragment_data_panel)).commit();
//Switch to data panel since it already exists
panelManager.beginTransaction().attach(fragmentData).commit();
} else if(panel_id == 2){
//detach any panel attached to the fragment_data_panel
panelManager.beginTransaction().detach(getFragmentManager().findFragmentById(R.id.fragment_data_panel)).commit();
//Switch to log panel
if(log_panel == false){
//If log panel is false, create log_panel for the first time
log_panel = true;
panelManager.beginTransaction().add(R.id.fragment_data_panel, fragmentLog).commit();
} else {
//Log_panel exists, so just attach fragment back
panelManager.beginTransaction().attach(fragmentLog).commit();
}
} else if(panel_id == 3){
//detach any panel attached to the fragment_data_panel
panelManager.beginTransaction().detach(getFragmentManager().findFragmentById(R.id.fragment_data_panel)).commit();
//Switch to graph panel
if(graph_panel == false){
//If log panel is false, create graph_panel for the first time
graph_panel = true;
panelManager.beginTransaction().add(R.id.fragment_data_panel, fragmentGraph).commit();
} else {
//Log_panel exists, so just attach fragment back
panelManager.beginTransaction().attach(fragmentGraph).commit();
}
}
}
//Call updateList method in FragmentLog to update ListView
#Override
public void app_log_update(String data, int icon) {
FragmentLog fragmentLog = (FragmentLog)getFragmentManager().findFragmentById(R.id.fragment_data_panel);
fragmentLog.updateList(data, icon);
}
}
FragmentData.java
public class FragmentData extends Fragment implements View.OnClickListener{
public EditText message_text;
public TextView display_message;
public Button button;
public String return_message = null;
boolean has_text_entered = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
return_message = savedInstanceState.getCharSequence("savedText").toString();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_data, container, false);
button = (Button)view.findViewById(R.id.set_text_button);
button.setOnClickListener(this);
display_message = (TextView) view.findViewById(R.id.display_message);
display_message.setText("This is a temp statement");
if(return_message != null){
display_message = (TextView) view.findViewById(R.id.display_message);
display_message.setText(return_message);
}
return view;
}
#Override
public void onClick(View v) {
has_text_entered = true;
message_text = (EditText)getActivity().findViewById(R.id.text_message);
String message = message_text.getText().toString();
display_message = (TextView)getActivity().findViewById(R.id.display_message);
display_message.setText(message);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView text = (TextView)getActivity().findViewById(R.id.display_message);
CharSequence userText = text.getText();
if(userText != null){outState.putCharSequence("savedText", userText);}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
}
Thank you for the help everyone!

Categories

Resources