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 :)
Related
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);
}
I've just moved my button onCreatView from my activity_main.java file to the correct file - my ConvertFragment.java file.
Now that I've copy and pasted the code, I'm getting a red-x errors on all of my findViewById's... any thoughts?
thanks in advance!
public class ConvertFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_convert, container, false);
final EditText editDecimal = (EditText) findViewById(R.id.editDecimal);
final EditText editBinary = (EditText) findViewById(R.id.editBinary);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int decimal = Integer.valueOf(editDecimal.getText().toString());
editBinary.setText(Integer.toBinaryString(decimal));
}
});
return rootView;
}
}
It's because a fragment doesn't have a method findViewById().
You can either call that method on your activity:
getActivity().findViewById()
Or just use the layout that you've just inflated and find view's inside of it:
rootView.findViewById()
The 2nd one is better (IMO) as it doesn't rely on the activity.
i am new to android but i have problem using settext method . i have used settext method but when i load the project in emulator then the textview there is empty . it is blank screen i have no error while loading inside emulator
the code i have written is
package com.coded.fragments;
public class ChildFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
return rootView;
}
public void setText(String item) {
item = "<p>ABCDEFGHI</p><br><p>JKLMNOPQRSTUVWXYZ</p>";
TextView textview = (TextView) getView().findViewById(R.id.textView2);
textview.setText(Html.fromHtml(item));
}}
should i add any method to it and front end xml file i have written as this
activity_main.xml
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="216dp"
android:padding="10dp"
android:textAlignment="center"
android:textColor="#color/white" />
please friends check,let me know and thanks for your valuable time.
if i use this above code when i load it onto emulator it is giving blank screen there is no text displayed which i am passing from item from above code
Try this..
public class ChildFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
String item = "<p>ABCDEFGHI</p><br><p>JKLMNOPQRSTUVWXYZ</p>";
TextView textview = (TextView) rootView.findViewById(R.id.textView2);
textview.setText(Html.fromHtml(item));
return rootView;
}
Or
TextView textview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
textview = (TextView) rootView.findViewById(R.id.textView2);
String item = "<p>ABCDEFGHI</p><br><p>JKLMNOPQRSTUVWXYZ</p>";
setText(item);
return rootView;
}
public void setText(String item) {
textview.setText(Html.fromHtml(item));
}
I have a class that extends ListActivity where the list items respond to OnClick events. Adding an OnItemLongClickListener does not work. The onItemLongClick() function is not called (no log-output or Toast showing) but the normal OnClick() event is handled instead.
I want to display a contextual action bar upon long click. A minimum example using my code in a new project works fine. So my question is: What can possibly prevent the onItemLongClick() trigger from being triggered?
My minimum API is 11. I am also setting the listView to longClickable="true".
Activity code (selected functions):
public class EventListActivity extends ListActivity {
private ArrayList<Event> arrEvents = null;
private ArrayAdapter<Event> adpEvents = null;
private ActionMode mActionMode = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// only create list adapter and set it
arrEvents = new ArrayList<Event>();
adpEvents = new ArrayAdapter<Event>(this, android.R.layout.simple_list_item_activated_2, android.R.id.text1, arrEvents) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
text1.setText(arrEvents.get(position).getTitle());
text2.setText(arrEvents.get(position).getDateTimeFormatted());
return view;
}
};
setListAdapter(adpEvents);
// add CAB to ListView
setupCAB();
}
#Override
protected void onResume() {
super.onResume();
// populate list and refresh adapter
createEventList();
adpEvents.notifyDataSetChanged();
// if list empty show emtpy msg, otherwise hide it
setContentView(R.layout.activity_event_list);
TextView empty = (TextView) findViewById(R.id.text_empty);
if(arrEvents.isEmpty()) {
empty.setVisibility(View.VISIBLE);
} else {
empty.setVisibility(View.GONE);
}
}
private void setupCAB() {
// Important: to select single mode
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
// Called when the user long-clicks an item on the list
#Override
public boolean onItemLongClick(AdapterView<?> parent, View row, int position, long rowid) {
Log.w("EventListActivity", "Long click detected!");
Toast.makeText(EventListActivity.this, "Long click detected!", Toast.LENGTH_SHORT).show();
if (mActionMode != null) {
return false;
}
// Important: to mark the editing row as activated
getListView().setItemChecked(position, true);
// Start the CAB using the ActionMode.Callback defined above
mActionMode = EventListActivity.this.startActionMode(mActionModeCallback);
return true;
}
});
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.event_context, menu);
return true;
}
// Called when the user enters the action mode
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Disable the list to avoid selecting other elements while editing one
EventListActivity.this.getListView().setEnabled(false);
return true; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_share_event:
//TODO share event
mode.finish();
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
// Re-enable the list after edition
EventListActivity.this.getListView().setEnabled(true);
mActionMode = null;
}
};
}
activity_event_list.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".EventListActivity" >
<TextView
android:id="#+id/text_empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="#string/empty"
android:textAppearance="?android:attr/textAppearanceLarge"
android:visibility="gone" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:longClickable="true" >
</ListView>
</RelativeLayout>
If you have buttons responding to onClick() events inside your listview, you need to set the following in the container holding those buttons:
android:descendantFocusability="blocksDescendants"
If what you have are textviews, the problem is slightly trickier. See this: Focusable EditText inside ListView
This answer does not solve user1's question but the symptoms were similar my problem (i.e. OnItemClickListener was getting called but OnItemLongClickListener was not). I'm posting my answer here in case anyone else stumbles on this question like I did when trying to solve my problem.
I was using a ListView inside a Fragment and implemented the listener methods:
public class MyFragment extends Fragment implements OnClickListener,
OnLongClickListener, OnItemClickListener, OnItemLongClickListener {
Here is the onItemClick method that was working fine:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long rowId) {
Log.i("Chimee", "short click working");
}
And here is the onItemLongClick method that wasn't firing:
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
long rowId) {
Log.i("Chimee", "Long click working");
return false;
}
Of course the simple answer was that I forgot to setOnItemLongClickListener. I added it after the setOnItemClickListener that I had all along and then it worked fine.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.my_fragment, container, false);
lvSuggestions = (ListView) v.findViewById(R.id.lvSuggestions);
lvSuggestions.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lvSuggestions.setOnItemClickListener(this);
lvSuggestions.setOnItemLongClickListener(this); // Forgot this
...
}
When using a ListActivity or ListFragment there is no method you can override for the long-click, and getting access to the ListView is not possible in onCreateView(), since it is being controlled by the parent class.
So, to overcome this, I did this, since the getListView() command won't work until after the view is created:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecipeListView = this.getListView();
mRecipeListView.setOnItemLongClickListener(new ListView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long row_id) {
// Process the long-click
}
});
}
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)