I'm trying to make an ImageView button inside a fragment to open another fragment in a navigation drawer but I have encountered a problem where I can't set an OnCliCkListener to my ImageView button. I tried searching fixes on youtube but I can't seem to find a fix to my problem.
Here's the error
Here's the error as text
HomeFragment.java
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(getLayoutInflater());
return binding.getRoot();
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
binding.IVOrdersButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment OrdersFragment = new OrdersFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_dashboard, OrdersFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
public void onDestroy(){
super.onDestroy();
binding = null;
}
}
Dashboard_fragment.xml
<TextView
android:id="#+id/DashboardTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Dashboard"
android:textColor="#000000"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.051"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022" />
<ImageView
android:id="#+id/IVOrdersButton"
android:layout_width="76dp"
android:layout_height="89dp"
android:clickable="true"
android:focusable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/DashboardTV"
app:layout_constraintVertical_bias="0.074"
app:srcCompat="#drawable/ic_orders"
tools:srcCompat="#drawable/ic_orders" />
<TextView
android:id="#+id/OrdersLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ordersDashboard"
android:textColor="#000000"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.187"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/IVOrdersButton"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
You're inflating FragmentHomeBinding based on fragment_home.xml but the layout with the imageview is called Dashboard_fragment.xml. Move the ImageView to fragment_home.xml to be able to use it this way.
Check the code again, it is missing #Override before the onCreateView and onViewCreated functions
Related
I have created 3 fragments for one of my project ..this is one of them. So basically I want When ever the admin(aAccountFragment) will click on the update quote button the quote should be updated and should be reflected in AccountFragment.xml file in the user end.
For this in the admin(aAccountFragment) side I have provided and edit text where the admin can update the quote every 24hrs.and in the user end(AccountFragment) the user can only see the updated quote when ever the admin will update the quote because at user end textview is provided and in the admin end EditText is provided.
For this I have attached my aAccountFragment.xml, AccountFragment.xml,AccountFragment.java,aAccountFragment.java code.
This is my aAccountFragment.xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".aAccountFragment"
android:background="#drawable/ic_launcher_background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="339dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="41dp"
android:layout_marginBottom="465dp"
android:text=" QUOTE OF THE DAY"
android:textColor="#color/black"
android:textSize="30sp" />
<EditText
android:layout_width="323dp"
android:layout_height="111dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="21dp"
android:layout_marginBottom="273dp"
android:text="-She decided to start living the life she imagined-"
android:textColor="#color/DarkRed"
android:textSize="25sp" />
<Button
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="107dp"
android:layout_marginBottom="177dp"
android:background="#color/LightBlue"
android:text="UPDATE QUOTE"
android:textColor="#color/black"
android:textSize="20sp" />
<Button
android:id="#+id/logout1"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="43dp"
android:layout_marginBottom="75dp"
android:background="#color/Pink"
android:text="LOG OUT"
android:textColor="#color/black"
android:textSize="20sp" />
</RelativeLayout>
this is my aAccountFragment.java code.
public class aAccountFragment extends Fragment {
Button logout1;
public aAccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.afragment_account, container, false);
logout1 = view.findViewById(R.id.logout1);
logout1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), aloginpage.class));
Toast.makeText(getActivity().getApplicationContext(), "SUCCESSFULLY LOGOUT", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
this is my AccountFragment.xml code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AccountFragment"
android:background="#drawable/ic_launcher_background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="339dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="41dp"
android:layout_marginBottom="465dp"
android:text=" QUOTE OF THE DAY"
android:textColor="#color/black"
android:textSize="30sp" />
<TextView
android:layout_width="296dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="49dp"
android:layout_marginBottom="272dp"
android:text="-She decided to start living
the life she imagined-"
android:textColor="#color/DarkRed"
android:textSize="25sp" />
<Button
android:id="#+id/logout"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="28dp"
android:layout_marginBottom="75dp"
android:background="#color/Pink"
android:text="LOG OUT"
android:textColor="#color/black"
android:textSize="20sp" />
</RelativeLayout>
this is my AccountFragment.java code.
public class AccountFragment extends Fragment {
Button logout;
public AccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
logout = view.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), loginpage.class));
Toast.makeText(getActivity().getApplicationContext(), "SUCCESSFULLY LOGOUT", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
STEP-1: To take quote input from edittext inside AdminFragment.java. I am not posting it's xml file as nothing important there except an EditText. You can put it inside any Activity.
AdminFragment.java
public class AdminFragment extends Fragment {
public static AdminFragment newInstance() {
return new AdminFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
EditText quoteEditText = view.findViewById(R.id.quote_et);
Button quoteBtn = view.findViewById(R.id.quote_btn);
quoteBtn.setOnClickListener(v -> {
String quote = quoteEditText.getText().toString();
if (quote.isEmpty()){
Toast.makeText(getContext(),"Please Enter Quote!",Toast.LENGTH_SHORT).show();
}else {
Intent intent = new Intent(getActivity(), BottomNavigationActivity.class);
intent.putExtra("quote",quote);
startActivity(intent);
}
});
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
STEP-2:
As you would have declared BottomNavigationActivity which would have 3 fragments namely SnapFragment.java , HomeFragment.java and AccountFragment.java. Quote text will be received from AdminFragment.java while click on updateQuote button inside BottomNavigationActivity. Once quote is received inside BottomNavigationActivity, I am opening 3rd Fragment i.e AccountFragment to show quoted text.
BottomNavigationActivity.java
public class BottomNavigationActivity extends AppCompatActivity {
String updatedQuote = "";
BottomNavigationViewModel bottomNavigationViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
bottomNavigationViewModel = new ViewModelProvider(this).get(BottomNavigationViewModel.class);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_snap, R.id.navigation_home, R.id.navigation_account)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
updatedQuote = getIntent().getStringExtra("quote");
Log.d("tisha==>>","Quote = "+updatedQuote);
bottomNavigationViewModel.setQuoteLiveData(updatedQuote);
// Below I am selecting 3rd Fragment to show Quote
navView.setSelectedItemId(R.id.navigation_account);
}
}
activity_bottom_navigation.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
I am using ViewModel here, because it will be easier to pass quote data from current activity to AccountFragment.java as AccountFragment is not instantiated by it's constructor here. BottomNavigationViewModel is responsible for storing quote and provide wherever it is required.
BottomNavigationViewModel.java
public class BottomNavigationViewModel extends ViewModel {
private final MutableLiveData<String> quoteLiveData;
public String getQuoteLiveData(){
return quoteLiveData.getValue();
}
public void setQuoteLiveData(String quote){
quoteLiveData.setValue(quote);
}
public BottomNavigationViewModel(){
quoteLiveData = new MutableLiveData<>();
}
}
STEP-3:
Now inside AccountFragment, I just get the view model which is created inside BottomNavigationActivity and collecting quote from that and displaying it in TextView.
AccountFragment.java
public class AccountFragment extends Fragment {
private String mQuote;
private BottomNavigationViewModel bottomNavigationViewModel;
public AccountFragment() {
// Required empty public constructor
}
public static AccountFragment newInstance(String quote) {
return new AccountFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bottomNavigationViewModel = new ViewModelProvider(requireActivity()).get(BottomNavigationViewModel.class);
mQuote = bottomNavigationViewModel.getQuoteLiveData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_account, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
TextView quoteView = view.findViewById(R.id.quote_tv);
quoteView.setText(mQuote);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have designed a login page using Viewpager(login page and register page) and set a fragment to load on that ViewPager when using intend for login button to go the next page after login it crashes
note:I have simply made login button to intent to next page even there is nothing in username and password just to test everything works fine
Here is my Java coding:
public class LoginFragment extends Fragment{
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
final Button b = null;
b.findViewById(R.id.Loginbutton);
final EditText e = getView().findViewById(R.id.user);
EditText e1 = getView().findViewById(R.id.pass);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent l = new Intent(getActivity(), AfterLogin.class);
startActivity(l);
}
});
view = inflater.inflate(R.layout.fragment_login,container,false);
return view;
}
public LoginFragment() {}
}
There is no error but during runtime it makes the app crash...
Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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="#color/DefaultWhite">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="125dp"
android:text="#string/app_name"
android:textColor="#color/colorPrimaryDark"
android:textSize="30sp" />
<ImageView
android:contentDescription="#string/LoginText"
android:id="#+id/imageView4"
android:layout_width="48dp"
android:layout_height="57dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
app:srcCompat="#drawable/accountbox" />
<EditText
android:id="#+id/user"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="#string/LoginText"
android:gravity="center"
android:layout_marginLeft="20dp"
android:layout_marginTop="300dp"
android:layout_marginRight="20dp"
android:background="#drawable/loginpageloginedittext"
/>
<EditText
android:id="#+id/pass"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="#string/PasswordText"
android:gravity="center"
android:layout_marginEnd="20dp"
android:layout_marginTop="360sp"
android:background="#drawable/loginpageedittextpassword"
android:layout_marginStart="20dp"
android:inputType="textPassword"
/>
<Button
android:id="#+id/LoginButton"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="450dp"
android:background="#drawable/loginbutton"
android:layout_marginStart="20dp"
android:textColor="#color/DefaultWhite"
android:layout_marginEnd="20dp"
android:text="#string/LoginButton" />
<Button
android:id="#+id/registerbutton"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:background="#drawable/forgotpasswordbutton"
android:layout_marginTop="450dp"
android:layout_marginStart="215dp"
android:layout_marginBottom="10dp"
android:text="#string/ForgotPassword" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="600dp"
android:layout_marginStart="160dp"
android:hint="#string/KnowUsMore" />
</android.widget.RelativeLayout>
avoid view.findViewById() instead of getView() i edit your code and given below. check it...
Happy Coding ;-)
public class LoginFragment extends Fragment{
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_login,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Button b = view.findViewById(R.id.Loginbutton);
EditText e = view.findViewById(R.id.user);
EditText e1 = view.findViewById(R.id.pass);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent l = new Intent(getActivity(), AfterLogin.class);
startActivity(l);
}
});
super.onViewCreated(view, savedInstanceState);
}
public LoginFragment() {}
}
I want to create dynamic views with x number of rows for each CardView that gets created. To help illustrate my idea this image shows what I essentially want to do.
For each CardView I want to be able to put any amount of TableRows into the CardView. So one CardView could have 4 rows whereas the next CardView could have 2 rows and so on.
EDIT: Implementation
Essentially this view is replicated several times, I would like to minimise having to write seperate layouts for each CardView with x amount of rows like in the Card Storage implemenation which is more reusable than what I currently have. As I hit the limit here, I have posted a pastebin of the current layout with rows that I have
https://pastebin.com/9RFDGhXv
Layout: Card Storage
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
style="#style/CardStyle">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
style="#style/MainConstraints" >
<TableRow
android:id="#+id/row_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<TextView
android:id="#+id/card_title"
style="#style/Title"/>
</TableRow>
<TableRow
android:id="#+id/row_two"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toBottomOf="#+id/row_one"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<android.support.constraint.ConstraintLayout>
<ImageView
android:id="#+id/drawable"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
style="#style/RowDrawableElement"
/>
<TextView
android:id="#+id/percentage_descriptor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="#id/drawable"
android:text="#string/percentage_descriptor"
style="#style/RowTextElement" />
<TextView
android:id="#+id/percentage_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
style="#style/RowTextElement" />
</android.support.constraint.ConstraintLayout>
</TableRow>
<TableRow
android:id="#+id/row_three"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/row_two"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
style="?android:attr/progressBarStyleHorizontal"
/>
</TableRow>
<TableRow
android:id="#+id/row_four"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/row_three"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<android.support.constraint.ConstraintLayout>
<TextView
android:id="#+id/text_used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
/>
<TextView
android:id="#+id/text_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
</TableRow>
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
Adapter
public class StorageAdapter extends RecyclerView.Adapter<StorageAdapter.MyViewHolder> {
private Context mContext;
private List<StorageObjects> mList;
public StorageAdapter(Context context, List<StorageObjects> list) {
this.mContext = context;
this.mList = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_storage, parent, false);
return new MyViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
StorageObjects storageObjects = mList.get(position);
long used = storageObjects.getUsed();
long total = storageObjects.getTotal();
holder.mProgress.setMax(0);
holder.mProgress.setProgress(0);
holder.mTitle.setText(storageObjects.getTitle());
MiscUtils.testDrawableIdentifier(mContext.getApplicationContext(), holder.mImageViews, storageObjects.getDrawables());
holder.mPercentage.setText(storageObjects.getPercentage() + mContext.getString(R.string.percentage));
holder.mProgress.setMax((int) (total/100000));
holder.mProgress.setProgress((int) (used/100000));
holder.mUsed.setText(MiscUtils.humanReadableByteSize(used));
holder.mTotal.setText(MiscUtils.humanReadableByteSize(total));
}
#Override
public int getItemCount() {
return mList.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.card_title) TextView mTitle;
#BindViews({R.id.drawable}) List<ImageView> mImageViews;
#BindView(R.id.percentage_text) TextView mPercentage;
#BindView(R.id.progress_bar) ProgressBar mProgress;
#BindView(R.id.text_used) TextView mUsed;
#BindView(R.id.text_total) TextView mTotal;
MyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
Class Storage
public class Storage extends Fragment {
private Unbinder mUnbinder;
private List<StorageObjects> storageList;
private StorageAdapter adapter;
private RecyclerView.LayoutManager mLayoutManager;
#BindArray(R.array.storage_ic_images)
String mDrawables[];
#BindView(R.id.recycler_view)
RecyclerView mRecyclerView;
public Storage() {
// Required empty public constructor
}
public static Storage newInstance() {
return new Storage();
}
#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_storage, container, false);
mUnbinder = ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
initRecyclerView();
}
#Override
public void onDestroy() {
super.onDestroy();
mUnbinder.unbind();
}
private void initRecyclerView() {
storageList = new ArrayList<>();
adapter = new StorageAdapter(getActivity(), storageList);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager = ViewUtils.getLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(2, ViewUtils.dpToPx(
getActivity(), 10), true));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(adapter);
prepareView();
}
#SuppressLint("SetTextI18n")
private void prepareView(){
StorageObjects storage
= new StorageObjects(
getActivity().getString(R.string.int_storage_title),
StorageUtils.internalUsed(),
StorageUtils.internalTotal(),
StorageUtils.internalPercentage(),
mDrawables[0]);
storageList.add(storage);
storage = new StorageObjects (
getActivity().getString(R.string.ext_storage_title),
StorageUtils.externalUsed(getActivity()),
StorageUtils.externalTotal(getActivity()),
StorageUtils.externalPercentage(getActivity()),
mDrawables[1]
);
storageList.add(storage);
adapter.notifyDataSetChanged();
}
}
If number of rows per card view is less then you can inflate edit text and add it to linear layout.
Note : It's a bad practice to add scroll view inside a scroll view
I have created 2 fragment and their layout,
when i click button on profile fragment it should open flat layout, but
it force stop application and its not opening the second fragment,
i have included fragment code and its layout code..
profilefragment.java
public class ProfileFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.profile, container, false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onButtonClicked(v);
}
});
return rootView;
}
public void onButtonClicked(View view)
{
//do your stuff here..
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.button, new flatview(), "NewFragmentTag");
ft.commit();
}
profile.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}"
android:id="#+id/semester">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
flatview.java
public class flatview extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.flat, container, false);
}
flat.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="second fragement"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
logcat
06-19 07:57:56.945 26457-26457/com.idealdeveloper.saltechnical E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.idealdeveloper.saltechnical, PID: 26457
java.lang.ClassCastException: android.widget.Button cannot be cast to android.view.ViewGroup
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:917)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Try this I guess it will work for you
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}"
android:id="#+id/semester">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/fragmentLayout"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Class
public class ProfileFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.profile, container, false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onButtonClicked(v);
}
});
return rootView;
}
public void onButtonClicked(View view)
{
//do your stuff here..
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragmentLayout, new flatview(), "NewFragmentTag");
ft.commit();
}
I hope this one will helps you
The fragment transaction inserts a View into a ViewGroup, so you can't just replace a Button. You could just replace the parent semester, since it is a ViewGroup.
public void onButtonClicked(View view) {
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.semester, new flatview(), "NewFragmentTag");
ft.commit();
}
If your intention is also to remove the button, you will need to do it manually since the FragmentManager can only modify runtime transactions:
ViewGroup parent = (ViewGroup) getActivity().findViewById(R.id.semester);
parent.removeView(view);
You have to provide a ViewGroup root for the flat.xml layout , for example you can surround the TextView with a LinearLayout
flat.xml :
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="second fragement"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
</LinearLayout>
I have some fragments that are being added programatically with differing tags. Each holds a button with an xml onClick that gets passed a view. How do I identify which fragment was clicked from that view? Code is below.
NewFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_fragment, container, false);
TextView tv = (TextView) view.findViewById(R.id.name);
Bundle bundle = this.getArguments();
int index = bundle.getInt("index");
tv.setText(Integer.toString(index));
return view;
}
Activity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
for (int loop = 0; loop < 4; loop++) {
NewFragment fragment = new NewFragment();
Bundle args = new Bundle();
args.putInt("index", loop);
fragment.setArguments(args);
//tag set to value of loop here
ft.add(R.id.new_fragment, fragment, Integer.toString(loop));
}
ft.commit();
}
public void toggleEdit(View view) {
//How do I find clicked fragment?
}
new_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/test">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:layout_marginLeft="5dp"
android:padding="5dp"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
android:text="Test"
/>
</LinearLayout>
<!-- Button in question is below -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="#string/edit"
android:onClick="toggleEdit"
android:id="#+id/edit_button"
/>
</LinearLayout>
Have your Fragment define an interface which your activity implements. Give that interface a method with a string parameter, and onClick, pass in the current Fragment's tag.
See this guide on Fragment communication for more detail http://developer.android.com/training/basics/fragments/communicating.html