Fragment UI not getting displayed - android

Activity Layout : activity_text_entry.xml
<?xml version="1.0" encoding="utf-8" ?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/fragmentContainer_TextEntry"
/>
Fragment Layout : fragment_text_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<EditText
android:id="#+id/Text_Entry_Date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/choose_date_text"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
/>
<requestFocus />
<EditText
android:id="#+id/Text_Entry_Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/choose_title_text"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp" >
</EditText>
<EditText
android:id="#+id/Text_Entry_Content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
android:ems="100"
android:gravity="left|top"
android:hint="#string/enter_text_here"
android:inputType="textMultiLine" >
</EditText>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:gravity="center|bottom"
>
<Button
android:id="#+id/Text_Entry_Button_Save"
android:text="#string/action_Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
<Button
android:id="#+id/Text_Entry_Button_Cancel"
android:text="#string/action_Cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
</LinearLayout>
</LinearLayout>
Activity : TextEntryActivity
package com.app.journal_v001;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.widget.Toast;
public class TextEntryActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_entry);
FragmentManager m_fm_text_entry_activity = getSupportFragmentManager();
Fragment m_f_text_entry_activity = m_fm_text_entry_activity.findFragmentById(R.id.fragmentContainer_TextEntry);
if(m_f_text_entry_activity == null)
{
m_f_text_entry_activity = new Fragment();
m_fm_text_entry_activity.beginTransaction()
.add(R.id.fragmentContainer_TextEntry, m_f_text_entry_activity)
.commit();
}
}
}
Fragment : TextEntryFragment
package com.app.journal_v001;
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.Button;
import android.widget.Toast;
public class TextEntryFragment extends Fragment {
//private Button m_btn_Text_Entry_Save;
//private Button m_btn_Text_Entry_Cancel;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflate,ViewGroup parent,Bundle savedInstanceState)
{
View v = inflate.inflate(R.layout.fragment_text_entry, parent, false);
return v;
}
}
I am trying to render TextEntryFragment(fragment) from this TextEntryActivity(activity).
I have kept a series of toasts in various places to track and I can see my code is getting executed till FragmentManager's FragmentTransaction and after that it does not seem to call the Fragment's onCreate/onCreateView.
Can anyone point me whats wrong ?
When I execute I am not able to see the fragment UI being rendered.

remove
if(m_f_text_entry_activity == null)
{
m_f_text_entry_activity = new Fragment();
m_fm_text_entry_activity.beginTransaction()
.add(R.id.fragmentContainer_TextEntry, m_f_text_entry_activity)
.commit();
}
and replace with
m_fm_text_entry_activity.beginTransaction()
.add(R.id.fragmentContainer_TextEntry, m_f_text_entry_activity)
.commit();
==================EDIT==================================
Also
TextEntryFragment m_f_text_entry_activity=new TextEntryFragment();
instead of
Fragment m_f_text_entry_activity = m_fm_text_entry_activity.findFragmentById(R.id.fragmentContainer_TextEntry);

Related

I don't understand why and how i can fix soft keyboard open and close automatically in Fragment Android

I have added an AutoCompleteTextView to my android project but when I click on the AutoCompleteTextView, the keyboard appears and disappears in a second.
But if I click the AutoCompleteTextView and quickly click on some characters, the keyboard doesn't disappear.
I do not understand why. How can I fix it?
if you need another piece of code ask me.
This is the Fragment.java
package com.example.trasporti;
import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import com.example.trasporti.adapter.PlaceAutoSuggestAdapter;
import com.google.android.libraries.places.api.model.Place;
import com.here.sdk.core.errors.InstantiationErrorException;
import com.here.sdk.search.SearchEngine;
/**
* A simple {#link Fragment} subclass.
* Use the {#link LocationFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class LocationFragment extends Fragment {
View layoutView;
TextView text1,text2,text3;
public LocationFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static LocationFragment newInstance(String param1, String param2) {
LocationFragment fragment = new LocationFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
layoutView = inflater.inflate(R.layout.fragment_location,container,false);
MainActivity mainActivity = (MainActivity) getActivity();
Context context = mainActivity.getContextF();
AutoCompleteTextView autoCompleteTextView = layoutView.findViewById(R.id.autocomplete);
autoCompleteTextView.setAdapter(new PlaceAutoSuggestAdapter(context, android.R.layout.simple_list_item_1));
// text1 = layoutView.findViewById(R.id.TextView1);
//text2 = layoutView.findViewById(R.id.TextView2);
//text3 = layoutView.findViewById(R.id.TextView3);
return layoutView;
}
}
This is Fragment layout
<?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:gravity="center_horizontal"
android:background="#0F1D49"
tools:context=".LocationFragment">
<!-- TODO: Update blank fragment layout -->
<AutoCompleteTextView
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:background="#color/white"
android:shadowColor="#color/white"
android:textColorHint="#color/grey"
android:textColor="#color/black"
android:textSize="20sp"
android:hint="Cerca la destinazione"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/autocomplete"
/>
<!---<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/TextView1"
android:textColor="#color/white"
android:fontFamily="monospace"
android:padding="12dp"
android:layout_marginTop="32dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/TextView2"
android:textColor="#color/white"
android:fontFamily="monospace"
android:padding="12dp"
android:layout_marginTop="32dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/TextView3"
android:textColor="#color/white"
android:fontFamily="monospace"
android:padding="12dp"
android:layout_marginTop="32dp"
/>-->
</LinearLayout>
I have followed up your code and make it a demo but nothing happens just like you mentioned. If your view is static, then moving any code to the onActivityCreated method is not necessary. But when you - for instance, fill some lists from the adapter, then you should do it in the onActivityCreated method. Please check it out below:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AutoCompleteTextView editText = findViewById(R.id.autocomplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.custom_list_item, R.id.text_view_list_item, countriesList);
editText.setAdapter(adapter);
}
}
Your Fragment layout:
<?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:gravity="center_horizontal"
android:background="#0F1D49"
>
<AutoCompleteTextView
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:background="#color/white"
android:shadowColor="#color/white"
android:textColorHint="#color/teal_200"
android:textColor="#color/black"
android:textSize="20sp"
android:completionThreshold="1"
android:hint="Cerca la destinazione"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/autocomplete"
/>
</LinearLayout>
text_view_list_item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_view_list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#color/teal_200"
android:textSize="16sp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/teal_700" />
</LinearLayout>

Android Initial Login Screen then use fragments to swipe between screens once login is successful

I am trying to create an Android app, then has an initial login screen that detects if a user is Admin or User. Once logged in, the user (depending on their role) will see different tabs to swipe between. I have a basic app that starts with a login activity and the login to decipher the users roles (using static values for now). First part is ok. Now when I try to use Fragments after the login screen, I'm getting stuck.
I have a LoginActivity that has an onClikcListener on a button after user enters credentials. Depending on whether the user is Amin or General Users, it will just to a new activity either activity_vote_admin or activity_vote_user. At this point I am stuck. Any ideas if what I am trying to do is valid. Or is there a better way to do this. At the moment I am getting this error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.confidencevotefragmentrebuild/com.example.confidencevotefragmentrebuild.activity_vote_admin}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
LoginActivity (this is my main activity)
...
package com.example.confidencevotefragmentrebuild;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
private static EditText username;
private static EditText password;
public static TextView attempts;
private static Button submit_button;
int attempt_counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton();
}
public void loginButton() {
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
attempts = (TextView) findViewById(R.id.textView_Attempts);
//Reference button view
final Button submit_button = findViewById(R.id.submit_button);
// perform click event on button
submit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (username.getText().toString().equals("admin") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, activity_vote_admin.class);
startActivity(intent);
} else if (username.getText().toString().equals("user") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intentUser = new Intent(LoginActivity.this, activity_vote_user.class);
startActivity(intentUser);
} else {
Toast.makeText(LoginActivity.this, "User or Password incorrect",
Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts.setText(Integer.toString(attempt_counter));
if (attempt_counter == 0) {
Toast.makeText(LoginActivity.this, "Too many failed attempts, please close app and try again",
Toast.LENGTH_SHORT).show();
submit_button.setEnabled(false);
}
}
}
}
);
}
}
...
Activity_vote_admin
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class activity_vote_admin extends AppCompatActivity {
/**
* Field for selecting the number of confidence votes
*/
RatingBar mResults;
private RatingBar rBar;
Button mBtn;
/**
* Spinner field to enter the project name
*/
private Spinner mProjectSpinner;
/**
* Projects. The possible values are:
* stored locally - Needs to get values from a database. TODO
*/
int mProject = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote_main_admin);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
AdminFragmentPagerAdapter adapter = new AdminFragmentPagerAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
// initiate a rating bar
rBar = findViewById(R.id.rating_bar);
//float vote = rBar.getRating();
// Find all relevant views for user input
mResults = findViewById(R.id.rating_bar);
mProjectSpinner = findViewById(R.id.spinner_project);
// Run getRating method to get rating number from a rating bar
//getRating();
// Initiate button
mBtn = findViewById(R.id.voteButton);
// perform click event on button
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get values and then displayed in a toast
//String totalStars = "Total Stars:: " + RatingBar.getNumStars();
float vote = rBar.getRating();
String rating = "Rating : " + vote;
Toast.makeText(getApplicationContext(), rating + "\n", Toast.LENGTH_LONG).show();
}
});
projectSpinner();
}
// Setup the dropdown spinner that allows the user to select the role.
private void projectSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
ArrayAdapter projectSpinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.projects, android.R.layout.simple_spinner_item);
// Specify dropdown layout style - simple list view with 1 item per line
projectSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
// Apply the adapter to the project spinner
mProjectSpinner.setAdapter(projectSpinnerAdapter);
// Set the integer mSelected to the constant values
mProjectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if(mProjectSpinner.getSelectedItem() == "This is Hint Text");
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.nextGEMS1_5))) {
mProject = 0 ;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_6))) {
mProject = 1;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_7))) {
mProject = 2;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_8))) {
mProject = 3;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_9))) {
mProject = 4;
return;
}
else mProject = 0;
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mProject = 0; // User
}
});
}
}
...
activity_vote_main_admin.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">
<androidx.viewpager.widget.ViewPager
android:name="com.example.confidencevotefragmentrebuild.testFragment1"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
...
activity_login.xml
...
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".LoginActivity"
tools:showIn="#layout/activity_login">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/login_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="LOGIN"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/login_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="30dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp">
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/usericon"
android:hint="User Name"
android:inputType="textEmailAddress"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:drawableLeft="#drawable/lock"
android:hint="Password"
android:inputType="textPassword"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:paddingTop="5dp"
android:text="Forgot Password?" />
<Button
android:id="#+id/submit_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Sign in"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="20dp"
android:orientation="horizontal"
android:paddingTop="1dp">
<TextView
android:id="#+id/attempts_text"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="Number of attempts remaining: " />
<TextView
android:id="#+id/textView_Attempts"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="5" />
</LinearLayout>
<TextView
android:id="#+id/lnkRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:gravity="center"
android:paddingTop="30dp"
android:text="Register here"
android:textColor="#5fb0c9"
android:textSize="16sp" />
</LinearLayout>
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
...
AdminFragemntyPagerAdapter
...
package com.example.confidencevotefragmentrebuild;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class AdminFragmentPagerAdapter extends FragmentPagerAdapter {
public AdminFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new testFragment1();
} else if (position == 1) {
return new testFragment2();
} else {
return new testFragment2();
}
}
#Override
public int getCount() {
return 3;
}
}
...
aactivity_vote_user.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/vote_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="USER VOTE"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/vote_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="70dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<Spinner
android:id="#+id/spinner_project"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:hint="#string/spinner_hint"
android:maxLines="1"
android:singleLine="true"
android:backgroundTint="#color/attCobalt"
android:popupBackground="#color/myBlue"
android:dropDownSelector="#color/attBlue"
/>
</com.google.android.material.textfield.TextInputLayout
>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<RatingBar
android:id="#+id/rating_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stepSize="1.0"
android:layout_marginTop="40dp"
android:theme="#style/rating_bar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="5dp"
android:text="Vote and Submit" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/voteButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
/>
</LinearLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
...
My fragments are as follows.
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
public class testFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_vote_user, container, false);
}
}
...
There are two reason for this issue :
You didn't declare any button on "activity_vote_main_admin.xml", thats why your view not binding with activity and giving null pointer exception.
May be you declare the button on fragment xml and trying to bind it with activity.

how to move main content and action bar to right in navigation drawer using fragments

i have a custom navigation drawer that opens from left to right using fragment. i want to move my content and action bar to right when navigation opens, i read some sources, they override onDrawerSlide method to do so, but since i using fragment to open and close navigation, i do not have such a method to override, I'll be grateful someone could help me (:
I tried this link to move the contents
and used this to create a custom navigation view
there is main activity :
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container">
<TextView
android:id="#+id/homeContents"
android:text="this is gonna be ur main page"
android:layout_width="200dp"
android:layout_height="46dp" />
</FrameLayout>
</LinearLayout>
and this is drawer :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/rootLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="250dp"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/nav_profile"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:layout_width="77dp"
android:layout_height="77dp"
android:src="#drawable/ic_user"
/>
<LinearLayout
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:drawableLeft="#drawable/ic_user_plus"
android:drawablePadding="5dp"
android:paddingLeft="10dp"
android:id="#+id/sign_in"
android:layout_width="91dp"
android:layout_height="40dp"
android:layout_marginStart="20dp"
android:background="#drawable/more_btn_coop_req"
android:text="SIGNUP"
android:textColor="#color/blue" />
<Button
android:drawableLeft="#drawable/ic_sign_in_alt"
android:drawablePadding="5dp"
android:paddingLeft="10dp"
android:id="#+id/sign_up"
android:layout_width="91dp"
android:layout_height="40dp"
android:layout_marginStart="25dp"
android:background="#drawable/more_btn_coop_req"
android:text="ENTER"
android:textColor="#color/blue" />
</LinearLayout>
<Spinner
android:layout_marginTop="16dp"
android:background="#drawable/spinner_background"
android:id="#+id/cities_spinner"
android:layout_gravity="center"
android:layout_width="190dp"
android:layout_height="40dp">
</Spinner>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_marginTop="250dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:drawableLeft="#drawable/ic_check"
android:drawablePadding="25dp"
android:id="#+id/bookmark_centers"
android:layout_gravity="center"
android:background="#drawable/drawer_buttons_style"
android:text="تخفیف های نشان شده"
android:layout_width="186dp"
android:layout_height="40dp" />
<Button
android:drawableLeft="#drawable/ic_store"
android:id="#+id/followed_centers"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:background="#drawable/drawer_buttons_style"
android:text="مراکز دنبال شده"
android:layout_width="186dp"
android:layout_height="40dp" />
<Button
android:id="#+id/tems"
android:drawableLeft="#drawable/ic_info"
android:background="#drawable/drawer_buttons_style"
android:layout_marginTop="20dp"
android:layout_gravity="center"
android:text="شرایط استفاده"
android:layout_width="186dp"
android:layout_height="40dp" />
<Button
android:id="#+id/contact_us"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:drawableLeft="#drawable/ic_phone"
android:background="#drawable/drawer_buttons_style"
android:text="ارتباط با ما"
android:layout_width="186dp"
android:layout_height="40dp" />
<Button
android:id="#+id/share_us"
android:layout_gravity="center"
android:text="پیشنهاد به دوستان"
android:layout_marginTop="10dp"
android:drawableLeft="#drawable/ic_share_alt"
android:background="#drawable/drawer_buttons_style"
android:layout_width="186dp"
android:layout_height="40dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<Button
android:id="#+id/EXIT"
android:layout_width="72sp"
android:layout_height="40dp"
android:layout_marginStart="32dp"
android:background="#drawable/drawer_buttons_style"
android:drawableLeft="#drawable/ic_sign_out_alt"
android:text="خروج" />
<Button
android:id="#+id/edit"
android:layout_width="105dp"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:background="#drawable/drawer_buttons_style"
android:drawableLeft="#drawable/ic_cog"
android:text="ویرایش" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
there is a custom toolbar and base activity that merged both toolbar and
drawer, but i think it is not necessary.
this is menu fragment class :
package TestNavigationDrawer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.example.deathstroke.uniqueoff1.R;
public class MenuFragment extends Fragment implements
View.OnTouchListener {
GestureDetector gestureDetector;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.slider_menu, container,
false);
RelativeLayout root = rootView.findViewById(R.id.rootLayout);
/*gestureDetector=new GestureDetector(getActivity(),new
OnSwipeListener(){
#Override
public boolean onSwipe(Direction direction) {
if (direction==Direction.up){
//do your stuff
((MainActivity ) getActivity()).hideFragment();
}
if (direction==Direction.down){
//do your stuff
}
return true;
}
});
root.setOnTouchListener(this);*/
return rootView;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
}
and there is mainActivity class :
package com.example.deathstroke.uniqueoff1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import TestNavigationDrawer.*;
public class MainActivity extends BaseActivity {
boolean isFragmentLoaded;
Fragment menuFragment;
TextView title;
ImageView menuButton;
RelativeLayout rootLayout;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.e("onCreate", "onCreate: " );
super.onCreate(savedInstanceState);
initAddlayout(R.layout.activity_main);
Log.e("onCreate", "onCreate: " );
rootLayout = findViewById(R.id.rootLayout);
textView = findViewById(R.id.homeContents);
title = findViewById(R.id.title_top);
menuButton = findViewById(R.id.menu_icon);
title.setText("Menu Activity");
menuButton.setOnClickListener((View)-> {
try {
if (!isFragmentLoaded) {
loadFragment();
title.setText("Profile");
} else {
if (menuFragment != null) {
if (menuFragment.isAdded()) {
hideFragment();
}
}
}
}catch (Exception e){
Log.e("Menu", "onCreate: menu on click, e: " + e);
}
});
}
public void hideFragment(){
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_left,
R.anim.slide_right);
fragmentTransaction.remove(menuFragment);
fragmentTransaction.commit();
menuButton.setImageResource(R.drawable.ic_menu);
isFragmentLoaded = false;
title.setText("Main Activity");
}
public void loadFragment(){
FragmentManager fm = getSupportFragmentManager();
menuFragment = fm.findFragmentById(R.id.container);
menuButton.setImageResource(R.drawable.ic_up_arrow);
if(menuFragment == null){
menuFragment = new MenuFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_left,
R.anim.slide_right);
fragmentTransaction.add(R.id.container,menuFragment);
fragmentTransaction.commit();
}
isFragmentLoaded = true;
}
}
as you can see, i am using loadFragment and hideFragment to open and close drawer, so how can i move main content (there is a simple textview but consider it whole lots of stuff)
Hey you can use this I guess you want the same output
The below link

My Android Application Is Giving Fragment Not Attached To Activity Error.

//Here Is My Code
My target is to add a custom listview on fragment and fire it on activity creation
// FragmentSongs.java
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class FragmentSongs extends ListFragment implements OnItemClickListener {
ListView listview;
String[] Songs=getResources().getStringArray(R.string.songs);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MyAdapter adapter=new MyAdapter(getActivity(),Songs);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
View myview=inflater.inflate(R.layout.fragment_songs, container,false);
return myview;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getActivity(), Songs[position], Toast.LENGTH_SHORT).show();
}
}
// MyAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<String>{
Context context;
String[] songs;
LayoutInflater inflater;
public MyAdapter(Context context,String[] songs) {
super(context,R.layout.songlist_row);
this.context=context;
this.songs=songs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.songlist_row, null);
}
TextView tv1=(TextView) convertView.findViewById(R.id.textView1);
tv1.setText(songs[position]);
return convertView;
}
}
// MainActivity.java
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.print("Reached");
FragmentSongs songs=new FragmentSongs();
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction transaction=fm.beginTransaction();
transaction.add(R.id.fragment1,songs);
transaction.commit();
}
}
// activitymain.xml
<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="wrap_content"
android:id="#+id/activitylayout"
android:orientation="vertical">
<fragment
android:id="#+id/fragment1"
android:name="android.app.ListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
//
this is the name of my fragment which i want to attach to activitymain
fragment_songs.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:baselineAligned="false" >
<ListView
android1:id="#+id/listView1"
android1:layout_width="match_parent"
android1:layout_height="0dp"
android1:layout_weight="1" >
</ListView>
</LinearLayout>
// songlist_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:background="#1A237E" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="Large Text"
android:background="#C5CAE9"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:background="#C5CAE9"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignRight="#+id/textView1"
android:layout_toRightOf="#+id/textView2"
android:background="#C5CAE9"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
There are two ways of inserting a fragment of an activity and you are using both at the same time.
The first way is:
Declare the fragment inside the activity's layout file.
But in this case the fragment will be fixed on the activity like a view.
The second form is:
Programmatically add the fragment to an existing ViewGroup.
In this case you can add the fragment at any time to the activity, replace it with another fragment, remove the fragment when you want.
You can see what I'm telling you watching this link to the Android developer and looking "Adding a fragment to an activity".
Fragments Android Developers
Note: If you decide to programmatically add the fragment do not have to reference it in the XML Activity. On the other hand these lines would thus:
FragmentSongs songs=new FragmentSongs();
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction transaction=fm.beginTransaction();
transaction.add(R.id.content,songs);
transaction.commit();
R.id.content: It is the id of the container in which you add the fragment programmatically in your case on the activitymain.xml LinearLayout. As you can see you did not like this but you linked the id of the fragment which is a mistake.
Well do not forget that you should not use two ways of adding the fragments so pick one and hope that what prompted you find it useful.

Fragment and Toggle Button

I am very new to Android. I am trying to add a simple toggle button to a class which extends Fragment class.
I tried everything but I could not get it working. I managed to add a normal button but that is not useful for me.
All I want is add a toggle button.
Please help me.
Thanks all
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cccccc" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="Light Tab"
android:textColor="#333333"
android:textSize="20sp" />
<Button
android:id="#+id/fragment_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="61dp"
android:text="#string/btn_fragment" />
</RelativeLayout>
package com.baris.smartgame;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Light extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.light, container, false);
((Button) view.findViewById(R.id.fragment_button))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity,
R.string.toast_you_just_clicked_a_fragment,
Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
Use This as an Example :
<LinearLayout
android:id="#+id/txtDayTypes"
android:layout_below="#+id/main_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ToggleButton
android:id="#+id/tglDay1"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Saturday"
android:textOn="Saturday"
android:textOff="Saturday"
android:checked="true"/>
</LinearLayout>
and you can Access it by :
if(currentButton != R.id.tglDay1) ((ToggleButton)findViewById(R.id.tglDay1)).setChecked(false);

Categories

Resources