I want a addressCard to scroll down behind another FirstRowCard which are both fragments. I have the addressCard appear behind the other but it doesn't scroll down. I realise I have to use Object Animator and include a View in the arguments.
I was originally using:
View addressCard = (View) getView().findViewById(R.id.years_of_cooking_xp_cardView);
ObjectAnimator addressCard_Animator = ObjectAnimator.ofFloat(addressCard, "translationY", 0f, 258f);
But the addressCard just appears with no animation. General architecture is Main Activity creates a fragment called topRow_fragment. In topRow_fragment I've created an interface so when a User clicks on a button, it creates the addressCard fragment that is displayed underneath the topRow_fragment. When the User clicks the button, the other fragments disappear and this works fine. I've commented out some parts that I intend on actualising but until the initial animation is completed, I'll ignore them.
I think I haven't correctly identified the View associated with the addressCard and consequently no animation is able to be shown. Any help would be great thanks,
Here's the class:
public class topRow_fragment extends Fragment implements View.OnClickListener{
addressCard_fragment addressCard;
onTopLeftClicked mCallback;
int addressCardLaunch = 0;
String NextAddressCardAnimation = "SLIDE DOWN";
View layoutReturn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
layoutReturn = inflater.inflate(R.layout.firstrow_fragment, container, false);
ImageButton top_row_left_button = (ImageButton) layoutReturn.findViewById(R.id.imageLeft);
top_row_left_button.setOnClickListener(this);
return layoutReturn;
}
#Override
public void onClick(View v) {
addressCard = new addressCard_fragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id. Below_top_row_fragment_container, addressCard);
View addressCard = (View) getView().findViewById(R.id.years_of_cooking_xp_cardView);
ObjectAnimator addressCard_Animator = ObjectAnimator.ofFloat(addressCard, "translationY", 0f, 258f);
//CardView addressCard_View = (CardView) getView().findViewById(R.id.years_of_cooking_xp_cardView);
//ObjectAnimator addressCard_Animator = ObjectAnimator.ofFloat(addressCard_View, "translationY", 0f, 258f);
switch(v.getId()) {
case R.id.imageLeft:
if (addressCardLaunch == 0) {
fragmentTransaction.commit();
moveSecondRowAfterClick(0);
addressCard_Animator.setDuration(250);
addressCard_Animator.start();
moveSecondRowAfterClick(0);
addressCardLaunch = 1;
}
else if (addressCardLaunch == 1) {
switch (NextAddressCardAnimation) {
case "SLIDE DOWN":
NextAddressCardAnimation = "SLIDE UP";
moveSecondRowAfterClick(1);
//addressCard_Animator.setInterpolator(new SlideDownAnimationInterpolator());
//addressCard_Animator.setDuration(250);
//addressCard_Animator.start();
break;
case "SLIDE UP":
NextAddressCardAnimation = "SLIDE DOWN";
moveSecondRowAfterClick(0);
//addressCard_Animator.setDuration(250);
//addressCard_Animator.start();
break;
}
}
}
}
public interface onTopLeftClicked {
void moveSecondRow(int slidingAnimationStatus);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a;
if (context instanceof Activity) {
a = (Activity) context;
try {
mCallback = (onTopLeftClicked) a;
}
catch (ClassCastException e) {
throw new ClassCastException(a.toString() + " must implement onTopLeftClicked Interface");
}
}
}
#Override
public void onDetach() {
mCallback = null;
super.onDetach();
}
public void moveSecondRowAfterClick(int slidingAnimationStatus) {
mCallback.moveSecondRow(slidingAnimationStatus);
}}
Update01:
I included methods within the fragment class, slideUpAnimation and slideDownAnimation and this has resolved a NullPointerException that I had. Yet to successfully animate the addressCard upon initialisation or subsequent button clicks. This approach is more in line with encapsulation rather than calling the animations within the topRow_fragment class. I'm wondering if this could now relate to view constraints I've emplaced on the CardView in the respective XML file.
Main Activity XML where the fragments are called, both topRow_fragment and addressCard.
<?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"
tools:context="com.example.bryanjordan.settingsr11.MainActivity">
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.constraint.ConstraintLayout
android:layout_width="368dp"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="8dp"
android:id="#+id/constraintLayout"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent">
<RelativeLayout
android:id="#+id/Below_top_row_fragment_container"
android:layout_width="367dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
tools:layout_editor_absoluteY="16dp">
</RelativeLayout>
<RelativeLayout
android:id="#+id/Above_top_row_fragment_container"
android:layout_width="367dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="1dp">
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent">
<RelativeLayout
android:id="#+id/second_row_fragment_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="25dp"></RelativeLayout>
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
Update02: I've looked at how slideDownAnimation and slideUpAnimation work and these are both being called correctly but the View just isn't moving. This is clearly a problem regarding assignment - I think it stems from the way the fragments are called.
Firstly, topRow_fragment is called then when the User clicks on a button below_topRow_fragmentis created. I've been looking at using:
View layoutTest = layoutReturn.findViewById(R.id.Below_top_row_fragment_container);
View addressTestR2 = (View) layoutTest.findViewById(R.id.years_of_cooking_xp_cardView);
And having NullPointerException errors but this seems to be the right direction as I'd have to call the respective child fragments to get to the one I want before then assigning it.
Related
My weather app works by searching cities on it's search panel and this works quite well. The only problem is that if i click the next tabs(hourly and daily section) on my bottom navigation view and
click the search button there, it shows the following exception:
java.lang.ClassCastException: com.viz.lightweatherforecast.SecondFragment cannot be cast to com.viz.lightweatherforecast.FirstFragment
at com.viz.lightweatherforecast.Activity.HomeActivity$2.onClick(HomeActivity.java:94)
at android.view.View.performClick(View.java:7044)
at android.view.View.performClickInternal(View.java:7017)
at android.view.View.access$3200(View.java:784)
at android.view.View$PerformClick.run(View.java:26596)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6819)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
This error clearly indicates that the error is from this line on the activity:
FirstFragment firstFragment = (FirstFragment) navHostFragment.getChildFragmentManager().getFragments().get(0);
firstFragment.getWeatherData(textfield.getText().toString().trim());
So I tried adding this:
SecondFragment secondFragment = (SecondFragment) navHostFragment.getChildFragmentManager().getFragments().get(0);
secondFragment.getWeatherData(textfield.getText().toString().trim());
So that it can support my secondfragment, but it still gave the error. I have as well searched this site for an answer, but haven't found any solution.
To explain the app further, I have an activity that hosts 3 fragments(Firstfragment, Secondfragment, and Thirdfragment. The 1st is labeled Today, 2nd is Hourly and 3rd is Daily for the weather.
I'm not planning on using the hourly and daily tabs for now until later versions of the app.
My other fragments are currently empty(no code written on them), I just want to stick to only the today tab for now.
But fixing this error is necessary, just in case of users click it.
My Aim is just to ensure that it doesn't give such an error if I click the search button on those other tabs, please help.
My Activity code:
public class HomeActivity extends AppCompatActivity {
// Last update time, click sound, search button, search panel.
TextView time_field;
MediaPlayer player;
ImageView Search;
EditText textfield;
// For scheduling background image change(using constraint layout, start counting from dubai, down to statue of liberty.
ConstraintLayout constraintLayout;
public static int count=0;
int[] drawable =new int[]{R.drawable.dubai,R.drawable.central_bank_of_nigeria,R.drawable.eiffel_tower,R.drawable.hong_kong,R.drawable.statue_of_liberty};
Timer _t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// use home activity layout.
time_field = findViewById(R.id.textView9);
Search = findViewById(R.id.imageView4);
textfield = findViewById(R.id.textfield);
// find the id's of specific variables.
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
// host 3 fragments along with bottom navigation.
final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
assert navHostFragment != null;
final NavController navController = navHostFragment.getNavController();
NavigationUI.setupWithNavController(bottomNavigationView, navController);
// For scheduling background image change
constraintLayout = findViewById(R.id.layout);
constraintLayout.setBackgroundResource(R.drawable.dubai);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// run on ui thread
runOnUiThread(() -> {
if (count < drawable.length) {
constraintLayout.setBackgroundResource(drawable[count]);
count = (count + 1) % drawable.length;
}
});
}
}, 5000, 5000);
Search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// make click sound when search button is clicked.
player = MediaPlayer.create(HomeActivity.this, R.raw.click);
player.start();
getWeatherData(textfield.getText().toString().trim());
// make use of some fragment's data
FirstFragment firstFragment = (FirstFragment) navHostFragment.getChildFragmentManager().getFragments().get(0);
firstFragment.getWeatherData(textfield.getText().toString().trim());
}
private void getWeatherData(String name) {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<Example> call = apiInterface.getWeatherData(name);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(#NonNull Call<Example> call, #NonNull Response<Example> response) {
try {
assert response.body() != null;
time_field.setVisibility(View.VISIBLE);
time_field.setText("Last Updated:" + " " + response.body().getDt());
} catch (Exception e) {
time_field.setVisibility(View.GONE);
time_field.setText("Last Updated: Unknown");
Log.e("TAG", "No City found");
Toast.makeText(HomeActivity.this, "No City found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NotNull Call<Example> call, #NotNull Throwable t) {
t.printStackTrace();
}
});
}
});
}
}
Activity.xml code:
<?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"
android:id="#+id/layout"
android:background="#drawable/dubai"
tools:context=".Activity.HomeActivity">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_menu" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="409dp"
android:layout_height="599dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:navGraph="#navigation/my_nav"
/>
<EditText
android:id="#+id/textfield"
android:layout_width="250dp"
android:layout_height="35dp"
android:autofillHints="#string/change_city"
android:background="#color/colorPrimary"
android:hint="#string/search_city"
android:inputType="text"
android:labelFor="#id/imageView4"
android:padding="8dp"
android:textColor="#color/colorAccent"
android:textSize="16sp"
app:layout_constraintEnd_toStartOf="#+id/imageView4"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="50dp"
android:layout_height="35dp"
android:layout_marginEnd="1dp"
android:contentDescription="#string/searchbtn"
android:src="#drawable/look"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/time_field"
android:visibility="gone"
android:textColor="#FFFFFF"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textfield" />
</androidx.constraintlayout.widget.ConstraintLayout>
To get a correct reference to the displayed fragment from NavHostFragment you have to check the Fragment Class Type first before you try to downcast it.
Based on your question:
App crashes when I click the search button in my other fragments
You cannot retrieve always the FirstFragment or SecondFragment instance as the visible Fragment when switching between other fragments.
So simply change your code to be like below:
Fragment currentFragment = (Fragment) navHostFragment.getChildFragmentManager().getFragments().get(0);
if(currentFragment instanceof FirstFragment) {
FirstFragment firstFragment = (FirstFragment)currentFragment;
firstFragment.getWeatherData(textfield.getText().toString().trim());
}
else if(currentFragment instanceof SecondFragment) {
SecondFragment secondFragment = (SecondFragment)currentFragment;
secondFragment.getWeatherData(textfield.getText().toString().trim());
}
else if(currentFragment instanceof ThirdFragment) {
ThirdFragment thirdFragment = (ThirdFragment)currentFragment;
thirdFragment.getWeatherData(textfield.getText().toString().trim());
}
I have MainActivity and added 2 fragments in R.id.container.
The MainActivity looks like the following.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, Fragment1.newInstance())
.commit();
getSupportFragmentManager().beginTransaction()
.add(R.id.container, Fragment2.newInstance())
.commit();
}
}
Fragmnet1 and Fragment2 have the same code with different layouts.
public class Fragment1 extends Fragment {
public static Fragment1 newInstance() {
return new Fragment1();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_1, container, false);
}
}
And the associated layout fragment1.xml is
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".ui.main.Fragment1">
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Layout for Fragment2 is fragmnet2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".ui.main.Fragment1">
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Test2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Here is the Debug GPU overdraw MainActivity after adding Fragment1 and Fragment2
See this image below. This is the one more drawing of GPU because the layout in Fragment1 remains in the MainActivity.
How can I add fragments without loading/showing the fragment below?
You are adding two fragments in the same container. This is the exact behaviour as per your code. If you need to show the fragment added later only, you need to replace the fragment instead of add.
I do not know the exact use case of yours. However, I guess you are trying to show fragment1 and fragment2 based on some checking. In that case, you might consider having two functions like the following in your MainActivity.
public boolean fragment1Loaded = false;
public void switchToFrag1() {
fragment1Loaded = true;
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Fragment1.newInstance())
.commit();
}
public void switchToFrag2() {
fragment1Loaded = false;
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Fragment2.newInstance())
.commit();
}
Now in the onCreate function, you need to call a function based on a condition which is necessary.
if (showFirstFragment) switchToFrag1();
else switchToFrag2();
You can do the switching whenever necessary from MainActivity.
Hope that helps!
Update
You can handle the back button click in your MainActivity and handle the logic by yourself. Override the onBackPressed function and then switch the fragments based on your necessity. For example, see the modified functions above. I am keeping a reference of which fragment is loaded in the screen right now. Then override the onBackPressed function like the following.
#Override
public void onBackPressed() {
if (fragment1Loaded) super.onBackPressed();
else switchToFrag1();
}
Hope you get the idea.
I am trying to animate a Cardview when FAB is pressed. I want to get circular animation. Initially Cardview is set to Invisible. But, it is trowing null object reference on CardView.setVisibility.
public class FeedFragment extends Fragment {
private FloatingActionButton floatingBtn;
private CardView cardView;
boolean flag = true;
public FeedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_feed, container, false);
floatingBtn = view.findViewById(R.id.floatBtn);
cardView = view.findViewById(R.id.cardView);
floatingBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(flag) {
// Check if the runtime version is at least Lollipop
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// get the center for the clipping circle
int cx = cardView.getWidth() / 2;
int cy = cardView.getHeight() / 2;
// get the final radius for the clipping circle
float finalRadius = (float) Math.hypot(cx, cy);
// create the animator for this view (the start radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(cardView, cx, cy, 0, finalRadius);
// make the view visible and start the animation
cardView.setVisibility(View.VISIBLE);
anim.start();
} else {
// set the view to visible without a circular reveal animation below Lollipop
cardView.setVisibility(View.VISIBLE);
}
flag = false;
} else {
// Check if the runtime version is at least Lollipop
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// get the center for the clipping circle
int cx = cardView.getWidth() / 2;
int cy = cardView.getHeight() / 2;
// get the initial radius for the clipping circle
float initialRadius = (float) Math.hypot(cx, cy);
// create the animation (the final radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(cardView, cx, cy, initialRadius, 0);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
cardView.setVisibility(View.INVISIBLE);
}
});
// start the animation
anim.start();
} else {
// set the view to visible without a circular reveal animation below Lollipop
cardView.setVisibility(View.VISIBLE);
}
flag = true;
}
}
});
return view;
}
}
Here is the XML code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.authent.authentication.FeedFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="bottom">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="208dp"
android:layout_gravity="bottom"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
app:cardCornerRadius="20dp"
android:visibility="gone">
<LinearLayout
android:id="#+id/linearReveal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="gone">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Ask a Query"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#00ccff"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Share Something"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#ff3300"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Post an MCQ"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#cc9900"/>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatBtn"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="end"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:src="#drawable/edit_nick_name" />
</LinearLayout>
Somebody help how to achieve circular animation. I am new to programming.
I also tried making LinearLayout INVISIBLE, it is also throwing NullPointerException on LinearLayout.setVisibility on a null object reference.
Thanks in advance.
Your CardView is null. Based on your code, you are trying to get the CardView from the View that received the onClick which is the FloatingButton.
Try calling the initialization outside just before the listener. Ideally on the same level as where you initialized the FloatingButton.
Intilaize cardview outside of the "clickListener".
You just need to remove this line cardView = view.findViewById(R.id.cardView);
and paste it before
floatingBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
return view;
}
I try to make a button active fragment, leading to a new layout with the url of this fragment. But it is not working. Something wrong. Please help
no receive error, but the button does not work.
code fragment
public class ContentFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.content_fragment, container, false);
final View button = view.findViewById(R.id.bSendUrl);
button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText simpleEditText = (EditText) getView().findViewById(R.id.bTextUrl);
String strValue = simpleEditText.getText().toString();
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("url", strValue);
startActivity(intent);
}
}
);
return view;
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TextInputLayout
android:id="#+id/input_TEXT_Url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_below="#+id/include"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_marginTop="6dp">
<EditText
android:id="#+id/bTextUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textUri"
android:hint="#string/url_edit_text" />
</android.support.design.widget.TextInputLayout>
<Button
android:layout_width="#dimen/latimea_button_send_tv"
android:layout_height="#dimen/inaltimea_button_send_tv"
android:text="#string/button_send_android_tv"
android:id="#+id/bSendUrl"
style="?android:attr/borderlessButtonStyle"
android:layout_below="#+id/input_TEXT_Url"
android:paddingLeft="16dp"
android:layout_marginLeft="16dp" />
</RelativeLayout>
Edit
I am removed openjdk and installed clean javasdk and is work fine
You are trying to find a reference to a Button before the fragment's view hierarchy is inflated. The fragment transaction you're using does not immediately create the view hierarchy after commit() is called. This means the view with id bTextUrl is not yet created and findViewById() returns null.
Also, it's kind of strange for an activity to be messing with the views of child fragments. I recommend that you modify the views of the fragment within the fragment itself (not within the containing activity like you're doing now).
I have three Framgments inside a Viewpager and I want to start a new Activity from one of them with a button click. I also want to take some information with me from four Spinner elements. I am able to get the information from the Spinners and save in global variables but when I click the button the variables become null. I just can't figure this out and it's driving me mad!
Here is how I make the Fragments and find the correct layout XML:
public class SlideFragment extends Fragment {
private int currentPageNumber;
private View mainView;
public static SlideFragment create(int pageNumber, String origin) {
SlideFragment myFragment = new SlideFragment();
Bundle args = new Bundle();
args.putInt("page", pageNumber);
args.putString("origin", origin);
myFragment.setArguments(args);
return myFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentPageNumber = getArguments().getInt("page");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String origin = getArguments().getString("origin");
// This is the mainActivity
Rastimar rastimar = new Rastimar();
if (origin == "profile") {
if (currentPageNumber == 0) {
mainView = inflater.inflate(R.layout.profile_screen1, container, false);
}
else {
mainView = inflater.inflate(R.layout.profile_screen2, container, false);
}
}
else if (origin == "rastimi") {
switch (currentPageNumber) {
case 0:
mainView = inflater.inflate(R.layout.rastimar, container, false);
rastimar.makeSpinners(mainView);
rastimar.makeListView(mainView);
break;
case 1:
mainView = inflater.inflate(R.layout.rastima_leit, container, false);
rastimar.makeSpinnersForRastimaLeit(mainView);
break;
case 2:
mainView = inflater.inflate(R.layout.rastima_yfirlit, container, false);
rastimar.makeExpandableListView(mainView);
rastimar.makeSpinnersForYfirlit(mainView);
break;
}
}
return mainView;
}
}
Here I get the data from the spinners, this works.
private class onSpinnerSelected implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// Find the spinner that was pressed by id
switch(parent.getId()) {
case R.id.dates:
selectedRastimaDate = parent.getItemAtPosition(pos).toString();
break;
case R.id.courses:
selectedCourse = parent.getItemAtPosition(pos).toString();
break;
case R.id.spinner_start_time:
selectedStartTime = parent.getItemAtPosition(pos).toString();
break;
case R.id.spinner_end_time:
selectedEndTime = parent.getItemAtPosition(pos).toString();
break;
case R.id.spinner_dates:
selectedDate = parent.getItemAtPosition(pos).toString();
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
This is the method that is called when the button is pressed, all the variables in the putExtra method are all of a sudden null:
public void findAvailableTime(View view) {
Intent lausir_timar = new Intent(this, LausirTimar.class);
lausir_timar.putExtra("Date", selectedRastimaDate);
lausir_timar.putExtra("Course", selectedCourse);
lausir_timar.putExtra("StartTime", selectedStartTime);
lausir_timar.putExtra("EndTime", selectedEndTime);
startActivity(lausir_timar);
}
and this is the XML layout file for the Fragment
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="cityboys.golfapp.Rastimar">
<TextView
android:id="#+id/rastimaLeit_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dp"
android:textStyle="bold"
android:textColor="#2d7165"
android:layout_centerHorizontal="true"
android:text="Rástímaleit"
android:paddingBottom="10dp"/>
<Spinner
android:id="#+id/dates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rastimaLeit_title"
android:textColor="#2d7165"
android:layout_marginRight="5dp"
android:layout_alignParentLeft="true"/>
<Spinner
android:id="#+id/spinner_start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rastimaLeit_title"
android:textColor="#2d7165"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"/>
<Spinner
android:id="#+id/courses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/dates"
android:textColor="#2d7165"
android:layout_marginRight="5dp"
android:layout_alignParentLeft="true"/>
<Spinner
android:id="#+id/spinner_end_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_start_time"
android:textColor="#2d7165"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lausir tímar"
android:id="#+id/button"
android:layout_below="#+id/spinner_end_time"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:onClick="findAvailableTime" />
</RelativeLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#2d7165"
android:dividerHeight="0.5dp"
android:background="#2b574e" />
I'm not sure what more information I should give so if this is not enough just ask for more!
Thanks in advance.