Bind to Button in dynamic view - java

I try to code in java/android the first time and I am a bit frustrated that my years of c# knowledge do not seem to help me very much.
Currently I try to create a buttonclick-event that should be bound to a button that is inside a view that is loaded dynamicly.
Part of my activity:
private Button myButton;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String selectedMenu=getArguments().getString(ARG_SECTION_NUMBER);
if (selectedMenu==getString(R.string.title_test)) {
View rootView = inflater.inflate(R.layout.fragment_test, container, false);
myButton=rootView.findViewById("#+id/buttonTest"); // ERROR?
myButton.setOnClickListener(this);
return rootView;
}
return null;
}
public void onClick(View v) {
if (v==myButton) {
// magic stuff
}
}
And my button definition:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test starten"
android:id="#+id/buttonTest"
android:layout_gravity="center_horizontal"
android:onClick="TestSoap_OnClick" />
In the line "ERROR" I try to get the Button from the View. How can I access it?
And just for my understanding: As a button seems to be a view: Is "View" in Java about the same as "Control" in C# WinForms?

Replace
myButton = rootView.findViewById("#+id/buttonTest"); with myButton = (Button) rootView.findViewById(R.id.buttonTest);
The int that is expected is the id of the view that has been created which is referenced in R.id.

Try creating a function that will handle your onClick: in your case something like:
public void TestSoap_OnClick(View view){
doSomething();
}
Then when your button is pressed it will automatically call this function since you have:
android:onClick="TestSoap_OnClick"

try to remove the line android:onClick="TestSoap_OnClick" from your xml
and also replace myButton.setOnClickListener(this);
with myButton.setOnClickListener(onClick)

Related

Dialog for fragments

Why is my showPopup grey when I already have an OnClick method on that fragment's xml?
I'm trying to make the popup_about_app XML popup when I click on the button with the OnClick.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myDialog = new Dialog(getContext());
return inflater.inflate(R.layout.fragment_settings, container, false);
}
public void showPopup(View view) {
TextView txtclose;
myDialog.setContentView(R.layout.popup_about_app);
txtclose =(TextView) myDialog.findViewById(R.id.txtClose);
txtclose.setText("X");
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
In Android Studio, gray means its not being used yet. Either nothing is calling showPopup, or possibly that Android Studio isn't smart enough to find the thing calling showPopup (which can happen in various scenarios). I wouldn't worry about it unless you hit the button that's supposed to call showPopup and nothing happens (and then it means you forgot to call it). If the popup shows like you expect, its a non-issue.

Android - where to put onClick on linearlayout of a fragment

Obviously, I am new to Android - XML programming... So I have a navigation drawer, and once item is selected from the drawer, a corresponding fragment on the right side will display. Inside that fragment, I have linear layouts. I'd like to get redirected to another activity once that linear layout has been tapped. I was able to make it work on activities, by using android:onClick on XML file, but can't make it work on fragment. Somebody help me please.
App interface, refer to this image:
http://i.stack.imgur.com/u6dHi.jpg
Code:
fragment_smart.xml - the display once item's selected. I am trying to use the onClick on xml.
<LinearLayout
android:id="#+id/linearLayoutsmart1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_below="#+id/smart_title"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:weightSum="1"
android:onClick="smart_recommended_link">
Here's my Java code:
public class FragmentSmart extends Fragment {
public static final String TAG = "stats";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myfragment = inflater.inflate(R.layout.fragment_smart, container, false);
return myfragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void smart_recommended_link(View view) {
Intent smartRecommendedIntent = new Intent(this, SmartRecommended.class);
startActivity(smartRecommendedIntent);
}
}
The app is crashing when I clicked on the linearlayout using this code. What's the best thing to do here? Thank you!
For fragments you need to add the listener programmatically:
public class MyFragment extends Fragment implements View.OnClickListener {
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.my_layout).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Handle click based on v.getId()
}
}
First of all, linear layouts cant trigger onClick events by default.
Check this answer for more information: LinearLayout onClick.
You can get the LinearLayout from the view in your onCreateView() like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myfragment = inflater.inflate(R.layout.fragment_smart, container, false);
LinearLayout layout = (LinearLayout)myFragment.findViewById(R.id.linearLayoutsmart1);
// here you can set a listener of any type you want to the layout
return myfragment;
}
In fragments, you must use getActivity() method instead of this to reference the activity that the fragment is attached to.
public void smart_recommended_link(View view) {
Intent smartRecommendedIntent = new Intent(getActivity(), SmartRecommended.class);
startActivity(smartRecommendedIntent);
}

Android how to save all views in Fragment when user click on next and prev button

i use fragment for my application,they are : Fragment A, Fragment B and Fragment C.
to move from one fragment to another fragment, I use two buttons, the first button is used to move to the next fragment, and the second button is used to return to the previous fragment.
the problems when I move from one fragment to another fragment (such as from A to B and back to A and to B again and to C). all entries in the EditText that is in a fragment is lost and look back empty,it when I go back to the previous fragment, or when I want to go back to the next fragment. I've been using code addToBackStack () when switching to another fragment, indeed EditText that I made not lost when I press the back button on my phone, but it does not affect the buttons (Next And Prev) that I've created. this is Fragment A:
public class AFragment extends Fragment {
EditText text,text2;
public AFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
ImageView next=(ImageView)rootView.findViewById(R.id.next);
text=(EditText)rootView.findViewById(R.id.text);
text2=(EditText)rootView.findViewById(R.id.text1);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
getFragmentManager().beginTransaction().replace(R.id.frame_container, new BFragment()).addToBackStack(null).commit();
}
});
return rootView;
}
this is Fragment B:
public class BFragment extends Fragment {
EditText cut,cut2;
public BFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View Fragment B = inflater.inflate(R.layout.fragment_c, container, false);
ImageView next=(ImageView)rootView.findViewById(R.id.next);
ImageView prev=(ImageView)rootView.findViewById(R.id.prev);
cut=(EditText)rootView.findViewById(R.id.cut);
cut2=(EditText)rootView.findViewById(R.id.cut2);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
getFragmentManager().beginTransaction().replace(R.id.frame_container, new CFragment()).addToBackStack(null).commit();
}
});
prev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
getFragmentManager().beginTransaction().replace(R.id.frame_container, new AFragment()).addToBackStack(null).commit();
}
});
return Fragment B;
}
my question is how can i save view in Fragment when user click on next and prev button in my application? is there something missing in my code? i hope someone can help me to solve my problem. thank you very much.
Each fragments have various life cycle methods, you can use onDestroy method and save the required edit text view value calling Activity. For this expose some methods in the calling activity which can be access via fragment. Also else create a singleton class or use Shared Prefences.
I hope this helps.
try to change:
getFragmentManager().beginTransaction().replace(R.id.frame_container, new BFragment()).addToBackStack(null).commit();
to:
getFragmentManager().beginTransaction().add(R.id.frame_container, new BFragment()).addToBackStack(null).commit();

Dynamic value passing from numeric EditText to String in same Activity

This is a 2 part question. Firstable, I have this EditText which is strictly set that user can put numbers only by android:inputType="number". Like:
<EditText
android:id="#+id/edit_A1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:imeOptions="actionDone"
android:inputType="number"
android:hint="#string/zeroes" />
<TextView
android:id="#+id/act1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/act_string"
android:layout_centerVertical="true"
android:hint="000," />
What kind of output do I get from it? Is it normal String or Integer?
Secondly, I would like to set the TextView (code above) this way that when I input the number to the EditText and hit OK button from the appeared numpad, the number will immediately appear in the TextView. Both EditText and TextView are in the same activity. I have the following code:
public static class MainSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
EditText mAcu1ET = (EditText) rootView.findViewById(R.id.edit_A1);
TextView mAcu1TV = (TextView) rootView.findViewById(R.id.act1);
//????
return rootView;
}
}
to create the view. What kind of onClickListener should I implement so my TextView would change its value on OK button click from the EditText numpad? Still learning, go easy on me.
Title of the topic might be confusing, sorry!
Let me see if I got it, you want to write a number, press OK and see that number in both fields?
On button click:
String set = youreditText.getText().toString();
yourtextView.setText(set);
EditText, even if the inputType is in number, will only give you the keyboard configuration for number. You will always need to getText().toString() to get the input.
Edit text will always give you string but you can type cast it into number.
mAcu1ET.getText().toString();
Code:
public static class MainSectionFragment extends Fragment {
EditText mAcu1ET;
TextView mAcu1TV;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
mAcu1ET = (EditText) rootView.findViewById(R.id.edit_A1);
mAcu1TV = (TextView) rootView.findViewById(R.id.act1);
mAcu1ET.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
if(arg1==KeyEvent.KEYCODE_NUMPAD_ENTER){
mAcu1ET.setText(mAcu1TV.getText().toString());
}
return false;
}
});
return rootView;
}
}
You can use OnKeyListener
http://developer.android.com/reference/android/view/View.OnKeyListener.html
mAcu1ETt.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
/* do something */
}
}
});
Unfortunately, none of the above solutions worked. I found out the solution here: catching the "OK" button vs pressing "round-arrow" on EditText in Android
To sum up, my code would look like this:
public static class MainSectionFragment extends Fragment {
private EditText mAcu1ET;
private TextView mAcu1TV;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
mAcu1ET = (EditText) rootView.findViewById(R.id.edit_A1);
mAcu1TV = (TextView) rootView.findViewById(R.id.act1);
mAcu1ET.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction( TextView v, int actionId, KeyEvent event ) {
mAcu1TV.setText(mAcu1ET.getText().toString());
return false;
}
});
return rootView;
}
}
Thanks for contributing! Raghandunan somehow led me to it, thanks :)

Have button action in fragment instead of main

I have an Android app where i'm using tabs (with ActionBarSherlock). So my main activity creates the tabs for me and from there i load in the fragment layouts.
In my MainActivity.java i create a tab (this is just a snippet):
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(
bar.newTab().setText("Fragment 1"),
MainMenuFragment.class, null);
My MainMenu.java looks like this:
public class MainMenuFragment extends SherlockFragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.mainmenu_fragment, container, false);
return view;
}
public void showMainMenu(View view)
{
Log.e("app", "olol: button!"); // never called!!
}
}
And this is mainmenu_fragment
<?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"
android:background="#000000" >
<Button
android:id="#+id/btnMenu"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="41dp"
android:text="#string/mainmenu"
android:onClick="showMainMenu" />
</RelativeLayout>
Now all i have to do is place the method showMainMenu(View view) somewhere. I thought this would go in the corresponding java file (MainMenuFragment.java in my case). But it only works when i put the method in the MainAvtivity.java file.
That means that all my button actions from all kinds of fragment layouts will go in one (the main) java file. Why can't i simply place it inside the java file that calls the Fragment layout..??
The short answers is (like already pointed out), you can't.
The only way to do this is by creating an onClick even listener. In the MainMenuFragment.java in the onCreate method, do something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.scan_fragment, container, false);
Button menuButton = (Button)view.findViewById(R.id.btnMenu);
menuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.e("app", "onclick listener");
}
});
return view;
}
You can remove the onClick attribute from the layout xml.
Now all I have to do is place the method showMainMenu() somewhere - this is wrong. Please, refer to the documentation of android:onClick :
For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
Seems You cannot place your callback somewhere, because framework won't be able to find that callback. If You're defining it inside Activity (which is actually, a Context), it's possible for View to find it back. Actually, View.java contains the following code:
case R.styleable.View_onClick:
if (context.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot " + "be used within a restricted context");
}
final String handlerName = a.getString(attr);
mHandler = getContext().getClass().getMethod(handlerName, View.class);
...
mHandler.invoke(getContext(), View.this);
Seems it's the only possible way to call callback defined in layout file with current android:onClick attribute specification.
I solved this using the following:
Fragment xml contains
android:onClick="myFunction"
Activity Contains
public void myFunction(View v)
{ getSupportFragmentManager().findViewById/Tag(...).myFunction(v); }
Fragment Code can then implement as below to have access to local data
public void myFunction(View v) {...}
Hope this helps.

Categories