Button does not respond - java

Ive got a Button in one of my Fragments. But it seems to be "not-clickable". There is no Log.d. Message when I click the Button (In another Fragment (Same onclicklistenercode) everything is fine.
For greater overview I added the whole Class and the part of my layout file which defindes the button.
public class ListViewFragment extends Fragment {
DbHelper mydb;
Button buttondeletedb;
Button buttonexport;
private EditText roomnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Context context = getContext();
mydb = new DbHelper(context);
buttondeletedb = (Button) view.findViewById(R.id.button_deletelist_list);
buttonexport = (Button) view.findViewById(R.id.button_export);
String dataList = mydb.getAllElements();
String [] dataListArray = dataList.split("\n");
List<String> dataListFinal = new ArrayList<>(Arrays.asList(dataListArray));
ArrayAdapter<String> dataListAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_datalist,
R.id.list_item_datalist_textview,
dataListFinal);
View rootView=inflater.inflate(R.layout.fragment_listview, container, false);
ListView dataListListView = (ListView) rootView.findViewById(R.id.datalist);
dataListListView.setAdapter(dataListAdapter);
buttondeletedb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("buttondeletelist", "clicked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
mydb.deleteAll();
}
});
return rootView;
}
}
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/deletelist"
android:id="#+id/button_deletelist_list"
android:layout_gravity="center_horizontal" />

You can not click the button because the root view of Fragment is not view, you returned rootView. The button is child view of view.
Change return rootView; to return view;.
It should work

//Remove rootView and return view instead of rootView
public class ListViewFragment extends Fragment {
DbHelper mydb;
Button buttondeletedb;
Button buttonexport;
private EditText roomnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Context context = getContext();
mydb = new DbHelper(context);
buttondeletedb = (Button) view.findViewById(R.id.button_deletelist_list);
buttonexport = (Button) view.findViewById(R.id.button_export);
String dataList = mydb.getAllElements();
String [] dataListArray = dataList.split("\n");
List<String> dataListFinal = new ArrayList<>(Arrays.asList(dataListArray));
ArrayAdapter<String> dataListAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_datalist,
R.id.list_item_datalist_textview,
dataListFinal);
// Change made here. replace view instead of rootView and remove rootView
ListView dataListListView = (ListView) view.findViewById(R.id.datalist);
dataListListView.setAdapter(dataListAdapter);
buttondeletedb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("buttondeletelist", "clicked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
mydb.deleteAll();
}
});
// Replace rootView with view.
return view;
}
}

Link between XML file and Class file of the Element (Button) is not there.Add this line in your onCreateView()
Button buttondeletedb = (Button) view.findViewById(R.id.buttonid);

Related

Android Studio Button onClick listener in Fragment

I'm a newbie and i tried to learn the navigation drawer.
I want to set a onClick listener on a button in Fragment but when i run the App, the button do nothing.
this is WeightFragment.java:
`
public class WeightFragment extends Fragment {
private FragmentWeightBinding binding;
private EditText edtNumber;
private Button addBtn;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
WeightViewModel weightViewModel =
new ViewModelProvider(this).get(WeightViewModel.class);
binding = FragmentWeightBinding.inflate(inflater, container, false);
View root = binding.getRoot();
View view = inflater.inflate(R.layout.fragment_weight, container, false);
addBtn = view.findViewById(R.id.addBtn);
edtNumber = view.findViewById(R.id.edtNumber);
String weight = String.valueOf(edtNumber.getText());
SimpleDateFormat sdf = new SimpleDateFormat("'Date\n'dd-MM-yyyy HH:mm:ss");
String currentDateAndTime = sdf.format(new Date());
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),weight + currentDateAndTime, Toast.LENGTH_SHORT).show();
}
});
final TextView textView = binding.txtDate;
weightViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
I've tried with:
public class WeightFragment extends Fragment implements View.OnClickListener
and implement the method but it doesn't work anyway.
It's because you are setting the onClickListener on a View that you throw away.
Here is the binding (pay attetion to the root):
binding = FragmentWeightBinding.inflate(inflater, container, false);
View root = binding.getRoot();
but you are setting the listener on a button that is in:
View view = inflater.inflate(R.layout.fragment_weight, container, false);
addBtn = view.findViewById(R.id.addBtn);
addBtn.setOnClickListener(...);
and at the end you return root;
The view that has the onClick listener is there, you create it but in the end it's thrown away.
Just replace view with binding and it will work.
public View onCreateView(
#NonNull LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
) {
WeightViewModel weightViewModel = new ViewModelProvider(this).get(WeightViewModel.class);
binding = FragmentWeightBinding.inflate(inflater, container, false);
View root = binding.getRoot();
addBtn = binding.addBtn;
edtNumber = binding.edtNumber;
String weight = String.valueOf(edtNumber.getText());
SimpleDateFormat sdf = new SimpleDateFormat("'Date\n'dd-MM-yyyy HH:mm:ss");
String currentDateAndTime = sdf.format(new Date());
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),weight + currentDateAndTime, Toast.LENGTH_SHORT).show();
}
});
final TextView textView = binding.txtDate;
weightViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}

problem with removing previous view in a fragment

i have created a fragment in android that contain 2 functions, the startview() is called at the beginning when the fragment is called, then when user click a button childfragment() is called. and at that point it should have remove the view from the startview() and then replacing it with the newview from childfragment(), and thats what i thought it would do. But instead it did not remove the old view and place the newview on top of the old view. even thought i already place mContainer.removeAllViews(); it did not remove the old view. what am i missing? please help.
here is the code
#SuppressLint("ValidFragment")
public class FragmentSideContent extends android.app.Fragment {
//private OnFragmentInteractionListener mListener;
Context context;
View view,trueview;
ListView listView;
ListAdapter listAdapter;
private LayoutInflater mInflater;
private ViewGroup mContainer;
int[] image = {1,2,3};
String[] titleText = {"one","two","three","one","two","three","one","two","three","one","two","three"};
String[] subTitleText = {"one","two","three","one","two","three","one","two","three","one","two","three"};
public FragmentSideContent(Context context) {
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,#Nullable Bundle savedInstanceState) {
mInflater = inflater;
mContainer = container;
startview();
return trueview;
}
public void startview(){
view = mInflater.inflate(R.layout.fragment_sidecontent,mContainer,false);
listView = (ListView) view.findViewById(R.id.noteList);
listAdapter = new ListAdapter(context,image,titleText,subTitleText);
listView.setAdapter(listAdapter);
trueview = view;
}
public void childfragment(){
mContainer.removeAllViews();
View newview = mInflater.inflate(R.layout.fragment_sidecontent,mContainer,false);
Fragment childFragment = new FragmentList(context);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.child_fragment_container, childFragment).commit();
mContainer.addView(newview);
mContainer.addView(trueview);
trueview = newview;
}
}
I recommend you put in your fragment layout some GroupView for do this.
fragment_layout.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
in yout Fragment.java
View view;
Framelayout fContainer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_layout, container, false);
return startView();
}
public View startview(){
fContainer = (Framelayout) view.findViewById(R.id.container);
listView = (ListView) view.findViewById(R.id.noteList);
listAdapter = new ListAdapter(context,image,titleText,subTitleText);
listView.setAdapter(listAdapter);
return view;
}
public void childfragment(){
fContainer.removeAllViews();
Fragment childFragment = new FragmentList(context);
FragmentTransaction transaction =
getChildFragmentManager().beginTransaction();
transaction.replace(R.id.container, childFragment).commit();
}
Now in your oncreateview of the other fragment (FragmentList) put the view that you want inflate.
FragmentList.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View newview = mInflater.inflate(R.layout.fragment_sidecontent,mContainer,false);
return newview;
}

Using Activity methods in Fragment

Hi I am an amateur in Android, and I've got huge problem with using activity methods in my fragment class.
I would like to implement setContentView, findViewById and getMenuInflater. Unfortunately, I don't know how to do it.
public class WagaFragment extends Fragment{
private Spinner fromSpinner, toSpinner;
private EditText fromEditText, toEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**setContentView**(R.layout.activity_main);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.units, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fromSpinner = (Spinner) **findViewById**(R.id.spinner_from);
toSpinner = (Spinner) **findViewById**(R.id.spinner_to);
fromSpinner.setAdapter(adapter);
toSpinner.setAdapter(adapter);
fromEditText = (EditText) **findViewById**(R.id.editText_from);
toEditText = (EditText) **findViewById**(R.id.editText_to);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(Color.YELLOW);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
**getMenuInflater()**.inflate(R.menu.menu_main, menu);
return true;
}
public void konwertuj(View view) {
// Get the string from the Spinners and number from the EditText
String fromString = (String) fromSpinner.getSelectedItem();
String toString = (String) toSpinner.getSelectedItem();
double input = Double.valueOf(fromEditText.getText().toString());
// Convert the strings to something in our Unit enu,
Konwerter.Jednostka fromJednostka = Konwerter.Jednostka.fromString(fromString);
Konwerter.Jednostka toJednostka = Konwerter.Jednostka.fromString(toString);
// Create a converter object and convert!
Konwerter konwerter = new Konwerter(fromJednostka, toJednostka);
double result = konwerter.convert(input);
toEditText.setText(String.valueOf(result));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
}
In Fragments "contentView" (in your meanign) is defined in public View onCreateView procedure.
According to your code:
you have to use
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
<your control> = <Control type> view.findViewById(<control id>)
For MenuInflater try this:
MenuInflater inflater = getActivity().getMenuInflater();
Try at onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_name, container, false);
fromSpinner = (Spinner) view.findViewById(R.id.spinner_from);
return view;
}

How to pass values from one Fragment to another in a ViewPager?

I'm completely new to Android programming. I'm writing an where there are two Fragments: Query and Results. There is a Button and an EditText in the Query Fragment. When the user clicks on the Button, the results from the EditText should be displayed in the TextView that is present the Results Fragment.
Here is the Main Activity (Starting Point):
public class StartingPoint extends FragmentActivity
{
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
viewPager = (ViewPager)findViewById(R.id.pager);
viewPager.setAdapter(new FragmentsPagerAdapter(getSupportFragmentManager()));
}
}
Here is the QueryFragment.java:
public class QueryFragment extends Fragment
{
EditText queryET, endpointET;
Button execute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.query_fragment, container, false);
queryET = (EditText) view.findViewById(R.id.sparqlQueryET);
endpointET = (EditText) view.findViewById(R.id.sparqlEndpointET);
execute = (Button) view.findViewById(R.id.executeButton);
execute.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String query = queryET.toString();
String endpoint = endpointET.toString();
Query q = QueryFactory.create(query, Syntax.syntaxARQ);
q.setOffset(1);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpoint, query);
ResultSet rs = qe.execSelect();
StringBuffer results = new StringBuffer();
List<String> columnNames = rs.getResultVars();
while(rs.hasNext())
{
QuerySolution qs = rs.next();
for(String var: columnNames)
{
results.append(var +":");
if(qs.get(var) == null)
results.append("{null}");
else if (qs.get(var).isLiteral())
results.append(qs.getLiteral(var).toString());
else
results.append(qs.getResource(var).getURI());
results.append('\n');
}
results.append("----------------\n");
}
qe.close();
}
});
return view;
}
}
Here is the ResultsFragment:
public class ResultsFragment extends Fragment
{
TextView r;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.results_fragment, container, false);
r = (TextView) view.findViewById(R.id.resultsTV);
return view;
}
}
Now my question is how do I pass the result processed in the onClick method (of the QueryFragment), which is a String, to the ResultsFragment where the String would be displayed in a TextView?
Simple approach will be : Make public static String field in parent activity. onClick method will set info into this value, and onCreateView result fragment will try to take it from there.
onClick(View v){
MainActivity.myResultString = "result code";
}
and get it when you need it;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.results_fragment, container, false);
r = (TextView) view.findViewById(R.id.resultsTV);
r.setText(MainActivity.myResultString);
return view;
}
Something like this. Its not completed solution but can help you ) good luck.

setBackgroundResource on ImageView return null

I'm using ListFragment in my android project. I decided to make a listView, each listview item consist of music frequency imageView. I will try to animate the imageView of music frequency. Each listView has a button called play, once the play is clicked, the music frequency start to animate.
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
lv = (ListView) v.findViewById(R.id.list);
mp = new MediaPlayer();
mp = null;
Song s1 = new Song("Love Story",(float) 2.5, onMusicPlayListener);
Song s2 = new Song("Sad Story",(float) 1.0, onMusicPlayListener);
Song s3 = new Song("Breakup Story",(float) 3.5, onMusicPlayListener);
songs = new ArrayList<Song>();
songs.add(s1);
songs.add(s2);
songs.add(s3);
adapter = new MusicListAdapter(getActivity(),songs);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
OnClickListener onMusicPlayListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = getListView().getPositionForView((LinearLayout)v.getParent());
animMusicFreq = (ImageView) v.findViewById(R.id.music_anim);
animMusicFreq.setBackgroundResource(R.anim.anim_music);
animMusicFreq.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) animMusicFreq.getBackground();
frameAnimation.start();
}
});
You are inflating your view inside onCreateView, but you don't pass it to the system. Instead you tell it to inflate its own (you return super). It doesn't make any sense.
You should return your v view like so:
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
// ...
return v;
}

Categories

Resources