buttons in fragment(android studio) - java

I'm working on my app, and came to a huge problem. I need to implement buttons in my fragments and can't find a normal solution that works. this is the code:
package com.example.konjicdiscover10;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class SettingsFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_settings, container, false);
}
}
and XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:paddingTop="60dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingBottom="14dp"
android:background="#color/white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/button"
android:layout_width="350sp"
android:layout_height="50sp"
android:layout_centerHorizontal="true"
android:textSize="11sp"
android:layout_marginVertical="20dp"
android:text="dark mode(in preparation)" />
<Button
android:id="#+id/button2"
android:layout_width="350sp"
android:layout_height="50sp"
android:layout_centerHorizontal="true"
android:layout_marginVertical="80dp"
android:text="Languages(in preparation)"
android:textSize="11sp"/>
</RelativeLayout>
</ScrollView>
basically what I'm looking for is that a buttons can lead to a new fragments or activities where content will be.

you need to add declare a View :
package com.example.konjicdiscover10;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
View view;
public class SettingsFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_settings, container, false);
Button myButton = view.findViewById(R.id.button);
myButton..setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//write what you want the button to do
}
});
return view;
}
}
add View :
View view;
And set the :
view = inflater.inflate(R.layout.fragment_settings, container, false);
and when you link your xml code with java you will use the 'view' like that :
myButton = view.findViewById(R.id.button);
finally you return the view
return view;

Related

Method <...> is missing in <...> or has incorrect signature

I keep getting Method 'onClickGreeting' is missing in 'Home' or has incorrect signature warning in XML file and the app crashes when clicking on the button.
I tried doing Clean Project but nothing changed.
The method was created first manually, then I tried Android studio's fix:
This created an identical signature to the one I already wrote.
Home.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import com.example.apptest.databinding.HomeBinding;
public class Home extends Fragment {
private HomeBinding binding;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = HomeBinding.inflate(inflater, container, false);
return binding.getRoot();
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.btnShowRandomPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(Home.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
public void onClickGreeting(View view) {
Context context = getContext();
CharSequence text = String.format(getResources().getString(R.string.greeting), binding.userName.getText());
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
home.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"
tools:context=".Home">
<Button
android:id="#+id/btn_generate_greeting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:onClick="onClickGreeting"
android:text="#string/button_show_greeting"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/user_name" />
</androidx.constraintlayout.widget.ConstraintLayout>
..........................................................................

Why is my Fragment Blank?

Heyy all! I'm trying to learn fragments while coding, and I'm attempting to switch one fragment with another. Whenever I click the next button, the current fragment is replaced with a blank one and I have no idea why!
MainActivity.Java:
package com.alexoladele.testingshit;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import layout.WelcomeScreenFragment;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Makes sure that the root_layout view is not null before doing anything
if (findViewById(R.id.root_layout) != null) {
// Makes sure that there's no saved instance before proceeding
if (savedInstanceState == null) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction manager = fm.beginTransaction();
manager
.add(R.id.root_layout, WelcomeScreenFragment.newInstance(), "welcomeScreen")
.commit();
}
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.alexoladele.testingshit.MainActivity">
</FrameLayout>
WelcomeScreenFragment.java:
package layout;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.alexoladele.testingshit.MainScreenFragment;
import com.alexoladele.testingshit.R;
// Declares WelcomeScreenFragment as subclass of fragment
public class WelcomeScreenFragment extends Fragment {
private static final String TAG = "WelcomeScreenFragment";
private Button startBtn;
// +++++++++++++++++++++ OVERRIDE - METHODS ++++++++++++++++++++++++++
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Attaches the Fragment
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
// Creates Fragment view for use
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_welcome_screen, container, false);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
startBtn = (Button) view.findViewById(R.id.start_screen_btn);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction
.replace(R.id.root_layout, MainScreenFragment.newInstance())
.addToBackStack(null)
.commit();
}
});
}
// +++++++++++++++++++++ User METHODS ++++++++++++++++++++++++++
// Method to create new instances of Fragment
public static WelcomeScreenFragment newInstance() {
return new WelcomeScreenFragment();
}
}
fragment_welcome_screen.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/welcome_screen_root"
tools:context="layout.WelcomeScreenFragment">
<TextView
android:id="#+id/start_screen_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="176dp"
android:fontFamily="monospace"
android:text="#string/welcome_message"
android:textAlignment="center"
android:textSize="13sp"
android:textStyle="bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1"
app:layout_constraintHorizontal_bias="0.6" />
<android.support.v7.widget.AppCompatButton
android:id="#+id/start_screen_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome_button"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="59dp"
app:layout_constraintTop_toBottomOf="#+id/start_screen_msg"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.5"
android:layout_below="#+id/start_screen_msg"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainScreenFragment.java:
package com.alexoladele.testingshit;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainScreenFragment extends Fragment {
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public static MainScreenFragment newInstance() {
return new MainScreenFragment();
}
}
fragment_main_screen.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_screen_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.alexoladele.testingshit.MainScreenFragment">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="163dp"
android:text="#string/main_screen_tempmsg"
android:textAlignment="center"
android:visibility="visible"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintTop_creator="1" />
</RelativeLayout>
you did not inflate your fragment_main_screen xml !
In your MainScreenFragment.java do that
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_screen, container, false);
return view;
}
Inflate layout for MainScreenFragment also like you did it for WelcomeScreenFragment.
while creating fragment, we need to attach fragment xml, same as we are attaching in activity, but the method is different.
Add below code in MainScreenFragment.java:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_main_screen, container, false);
// do your code here.
return view;
}

Tabs in a Fragment dont show up

I have read many questions here about tabs in a fragment, and did everything described here: https://developer.android.com/reference/android/support/v4/app/FragmentTabHost.html
i got no error and the app doesn't crash or something, but the fragment is just empty. The JobFragment class is a simple fragment with just one label, but it isn't displayed.
here is my java code:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AutoFragment extends Fragment{
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment_auto);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
JobFragment.class, null);
return mTabHost;
}
#Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
}
and here is my layout xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
Try changing this line to:
mTabHost.setup(getActivity(), getSupportFragmentManager(), R.layout.fragment_auto);

How do I change the textview of a Fragment from WITHIN the fragment itself?

I have a MainActivity that creates 3 Fragments. Once I got into the first Fragment, I wish to change the Textview I have in the layout of THIS Fragment, from within this Fragment. I cannot see the 'findViewbyId' method popping up in the IDE when I try to access the TextView this way. Can someone please help me out? Here is the code for the Fragment which I want to carry out the operation in called 'FragmentOne'. The code is for 'FragmentOne.jav'
package com.iotaconcepts.aurum;
import android.app.Activity;
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.TextView;
import android.widget.Toast;
import com.iotaconcepts.aurum.R;
import java.io.*;
import java.util.*;
public class OneFrangment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Fragment fc=getTargetFragment();
TextView tv=(TextView)fc.findViewById(R.id.textview);//NOT WORKING
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(getActivity().getAssets().open("symp.txt")));
String parse1;
while((parse1=br.readLine())!=null)
{
Toast.makeText(getActivity(), parse1, Toast.LENGTH_LONG).show();
tv.setText(parse1 + "\n");
}
}
catch(Exception e)
{
tv.append("wtf\n");
Toast.makeText(getActivity(),"SORRY!", Toast.LENGTH_LONG).show();
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
XML CODE:
<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="info.androidhive.materialtabs.fragments.OneFragment">
android:w
<TextView
android:id="#+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Hello"
/>
You need to assign the inflater.inflate method to a View before you can find views from it.
View v = inflater.inflate(R.layout.fragment_one, container, false);
TextView tv=(TextView)v.findViewById(R.id.textview);
...
return v;

onitemclicklistener in slide menu fragment

I'm using slidemenu in my project.
In my fragment i have a listview that reads some data from db.
My fragment:
package ir.monocode.azmooneEstekhdami;
import ir.monocode.azmoonEstekhdami.R;
import java.util.ArrayList;
import android.app.Fragment;
import android.content.res.Resources;
import android.os.Bundle;
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 QuestionsFragment extends Fragment {
public QuestionsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_questions, container, false);
/******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
// setListData();
// CustomListViewValuesArr.clear();
MySQLiteHelper db = new MySQLiteHelper(getActivity());
ArrayList<CatsModel> CustomListViewValuesArr = db.getAllCelebs();
Resources res = getResources();
// now you must initialize your list view
ListView listview = (ListView) view.findViewById(R.id.listView1);
//listview.setFastScrollEnabled(true);
/**************** Create Custom Adapter *********/
CustomAdapter adapter = new CustomAdapter(getActivity(),CustomListViewValuesArr, res);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// do things with the clicked item
Toast.makeText(getActivity(), ""+ position, Toast.LENGTH_LONG).show();
}
});
return view;
}
}
My fragment layout is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dedede"
android:orientation="vertical" >
<ImageView
android:id="#+id/cimageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/top"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp" >
</ListView>
</LinearLayout>
But when i want to use onitemclicklistener it doesn`t work. Where is my problem?
As you can see i use customapater and
public void onItemClick(int mPosition) {
// TODO Auto-generated method stub
}
in my main activity.
You need to add these properties for your custom list item row layout widgets which is already inflated in getView() method by you.
android:focusable="false"
android:focusableInTouchMode="false"

Categories