TEXTVIEW substantiation location - java

I am trying to make an android code that provide a different work for each button.
so when the user press on Button1 a Textview field provides " you pressed on Button1"
my question is about the correct place that I can instantiate the Textview ONLY ONCE as the only working place is inside the Button1 Function.
Java Code for a single button:
public void Button1(View view) {
final TextView textView=(TextView)findViewById(R.id.textView2);
textView.setText("You clicked the button 1");
}
total java code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void Button1(View view) {
final TextView textView=(TextView)findViewById(R.id.textView2);
textView.setText("You clicked the button 1");
}
public void Button2(View view) {
final TextView textView=(TextView)findViewById(R.id.textView2);
textView.setText("You clicked the button 2");
}
public void Button3(View view) {
final TextView textView=(TextView)findViewById(R.id.textView2);
textView.setText("You clicked the button 3");
}
public void Button4(View view) {
final TextView textView=(TextView)findViewById(R.id.textView2);
textView.setText("You clicked the button 4");
}
public void Button5(View view) {
final TextView textView=(TextView)findViewById(R.id.textView2);
textView.setText("You clicked the button 5");
}
public void Button6(View view) {
final TextView textView=(TextView)findViewById(R.id.textView2);
textView.setText("You clicked the button 6");
}
}
Total XML Code
<?xml version="1.0" encoding="utf-8"?>
<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/RelativeLayoutID"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.sherifsaleh.xmllayout.MainActivity"
tools:showIn="#layout/activity_main"
>
<Button
android:id="#+id/button3"
android:onClick="Button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:layout_above="#+id/button6"
android:layout_alignLeft="#+id/button6"
android:layout_alignStart="#+id/button6" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="Button6"
android:text="6"
android:id="#+id/button6"
android:layout_below="#+id/button2"
android:layout_alignLeft="#+id/button9"
android:layout_alignStart="#+id/button9" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:id="#+id/button9"
android:onClick="Button9"
android:layout_alignTop="#+id/button8"
android:layout_toRightOf="#+id/button8"
android:layout_toEndOf="#+id/button8" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8"
android:id="#+id/button8"
android:layout_below="#+id/button5"
android:layout_toRightOf="#+id/button4"
android:layout_toEndOf="#+id/button4"
android:onClick="Button8"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:onClick="Button2"
android:id="#+id/button2"
android:layout_above="#+id/button5"
android:layout_toRightOf="#+id/button1"
android:layout_toEndOf="#+id/button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="Button5"
android:text="5"
android:id="#+id/button5"
android:layout_below="#+id/button1"
android:layout_toRightOf="#+id/button1"
android:layout_toEndOf="#+id/button1" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:onClick="Button1"
android:layout_above="#+id/button4"
android:layout_alignLeft="#+id/button4"
android:layout_alignStart="#+id/button4" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:id="#+id/button4"
android:layout_above="#+id/button7"
android:layout_alignLeft="#+id/button7"
android:layout_alignStart="#+id/button7" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7"
android:id="#+id/button7"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/textView2"
android:layout_alignStart="#+id/textView2"
android:layout_marginBottom="90dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true"
android:text="New Text"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:textSize="50dp"/>
</RelativeLayout>

Try like this.
public class MainActivity extends AppCompatActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView2);
....
}
And your Button click method as
public void Button1(View view) {
textView.setText("You clicked the button 1");
}

1)First try to initialize your references in onCreate which loads once.So references to your views will initialize only once
eg-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOne = (Button) findViewById(R.id.btnOne);
btnTwo = (Button) findViewById(R.id.btnTwo);
textView = (TextView) findViewById(R.id.textView);
btnOne.setOnClickListener(this);
btnTwo.setOnClickListener(this);
}
2)Instead of calling seperate methods for each button apply click listeners on buttons as above mentioned
and implement View.OnClickListener and then
3)Override method
#Override
public void onClick(View v) {
Button b = (Button)v;
String buttonText = b.getText().toString();
textView.setText("You clicked on " + buttonText);
}
So the code in onClick is repeating in your case instead of writing each time seperately write it once and get text or you can set Tag of button and get it(in case when you want to set another value to textview instead of button text) and set to textview as i did in onClick.
It will reduce your efforts and increase your code reusability and redability too..!!!!!

Not super sure what your question is. If your asking if it's acceptable to do your findViewById in the button listener, it's acceptable but not optional. Every time you press the button the code runs. It's better to do it once in onCreate

Simply declare it at the start of your Activity
public class MainActivity extends AppCompatActivity {
private TextView textView2;
.....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
textView2 = (TextView) findViewById(R.id.textView2);}
.....
public void Button6(View view) {
textView2.setText("bla");
}
Is that what you asked for ?

Related

When I try to get the text of an EditText it throws a Null Pointer Exception. [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Okay, this is my first post to stack so please bear with me. I have searched and have tried many things. I think another set of eyes might see something I don't. I get the NPE when i call the getText() function. I have included my scaled down version of my code, but the same error is happening. I have even looked that I have the right View any help will be appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<Task> taskList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater2 = (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View customView2 = inflater2.inflate(R.layout.task_add_operations,null);
final PopupWindow mPopupWindow2 = new PopupWindow(customView2,
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT, true);
Button closeButton2 = (Button)customView2.findViewById(R.id.closeButton2);
closeButton2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
mPopupWindow2.dismiss();
}
});
Button addButton = (Button)customView2.findViewById(R.id.addButton);
addButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View customView2) {
EditText text = customView2.findViewById(R.id.editText);
//This is where my java.lang.NullPointerException pops
String title = text.getText().toString();
taskList = Task.addTask(taskList, title);
mPopupWindow2.dismiss();
}
});
mPopupWindow2.showAtLocation(findViewById(R.id.activityMain),
CENTER,0, 0);
}
});
}
task_add_operations.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<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="74dp"
android:text="Add Task"
android:textSize="18sp" />
<EditText
android:id="#+id/editText"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="text"
android:text="Title" />
<Button
android:id="#+id/closeButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText"
android:layout_below="#+id/editText"
android:layout_marginTop="28dp"
android:text="Cancel" />
<Button
android:id="#+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/closeButton2"
android:layout_alignBottom="#+id/closeButton2"
android:layout_alignEnd="#+id/editText"
android:layout_alignRight="#+id/editText"
android:text="Add Task" />
</RelativeLayout>
You need to Bind Your EditText Outside addButton.setOnClickListener
EditText text =(EditText) customView2.findViewById(R.id.editText);
OR Try this change the view name of public void onClick(View View2) method like below code
Button addButton = (Button)customView2.findViewById(R.id.addButton);
addButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View View2) {
EditText text = (EditText)customView2.findViewById(R.id.editText);
//This is where my java.lang.NullPointerException pops
String title = text.getText().toString();
taskList = Task.addTask(taskList, title);
mPopupWindow2.dismiss();
}
});
From looking at this other Stack Overflow post:
Null Pointer Exception - Getting EditText Value
Looks like you might want to try to declare the EditText in OnCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addButton = (Button)customView2.findViewById(R.id.addButton);
EditText text = customView2.findViewById(R.id.editText);
addButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View customView2) {
//This is where my java.lang.NullPointerException pops
String title = text.getText().toString();
taskList = Task.addTask(taskList, title);
mPopupWindow2.dismiss();
}
});

Notetoself Icon Add donn't appear

I'm new to Android Programming. I'm following the guide on Android Developers to get started with Android. When trying to run simple Note on the Emulator,the emulator Shows me an Errors... according the book musst appear a Icon and add a note ,,note that if you add a second note ,it will overwrite the first because i only have one Note object the Problem is that Icon Add donn't appear
dialog_new_note
<RelativeLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editTitle"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp"
android:hint="#string/title_hint" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editDescription"
android:layout_below="#+id/editTitle"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp"
android:hint="#string/description_hint"
android:inputType="textMultiLine" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/idea_checkbox"
android:id="#+id/checkBoxIdea"
android:layout_below="#+id/editDescription"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp"
android:checked="false" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/todo_checkbox"
android:id="#+id/checkBoxTodo"
android:layout_below="#+id/checkBoxIdea"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp"
android:checked="false" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/important_checkbox"
android:id="#+id/checkBoxImportant"
android:layout_below="#+id/checkBoxTodo"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp"
android:checked="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel_button"
android:id="#+id/btnCancel"
android:layout_marginTop="50dp"
android:layout_below="#+id/checkBoxImportant"
android:layout_toRightOf="#+id/editTitle"
android:layout_toEndOf="#+id/editTitle" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ok_button"
android:id="#+id/btnOK"
android:layout_alignTop="#+id/btnCancel"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="53dp"
android:layout_marginEnd="53dp" />
</RelativeLayout>
Dialog_show_note
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageViewTodo"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageViewImportant"
android:layout_toEndOf="#+id/imageViewImportant"
android:src="#drawable/ic_check_box_black_24dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageViewIdea"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageViewTodo"
android:layout_toEndOf="#+id/imageViewTodo"
android:src="#drawable/ic_wb_incandescent_black_24dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/txtTitle"
android:layout_below="#+id/imageViewIdea"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/txtDescription"
android:layout_marginTop="34dp"
android:layout_below="#+id/txtTitle"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:id="#+id/btnOK"
android:layout_marginBottom="101dp"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/txtTitle"
android:layout_alignStart="#+id/txtTitle" />
</RelativeLayout>
**menu_main.xml**
Content_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Note"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
string_xml
Note To Self
Settings
<string name="action_add">add</string>
<string name="title_hint">Title</string>
<string name="description_hint">Description</string>
<string name="idea_checkbox">Idea</string>
<string name="important_checkbox">Important</string>
<string name="todo_checkbox">To do</string>
<string name="cancel_button">Cancel</string>
<string name="ok_button">OK</string>
<string name="sound_checkbox">On or Of</string>
<string name="settings_title">Settings</string>
<string name="sound_title">Sound</string>
<string name="amims_title">Animation Speed</string>
<string name="rb_fast">Fast</string>
<string name="rb_slow">Slow</string>
<string name="rb_none">None</string>
</resources>
**DialogNewNote**
>
public class DialogNewNote extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_new_note, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription);
final CheckBox checkBoxIdea = (CheckBox) dialogView.findViewById(R.id.checkBoxIdea);
final CheckBox checkBoxTodo = (CheckBox) dialogView.findViewById(R.id.checkBoxTodo);
final CheckBox checkBoxImportant = (CheckBox) dialogView.findViewById(R.id.checkBoxImportant);
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView).setMessage("Add a new mNote");
btnCancel.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
// Handle the OK button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create a new note
Note newNote = new Note();
// Set its variables to match the users entries on the form
newNote.setTitle(editTitle.getText().toString());
newNote.setDescription(editDescription.getText().toString());
newNote.setIdea(checkBoxIdea.isChecked());
newNote.setTodo(checkBoxTodo.isChecked());
newNote.setImportant(checkBoxImportant.isChecked());
// Get a reference to MainActivity
MainActivity callingActivity = (MainActivity) getActivity();
// Pass newNote back to MainActivity
callingActivity.createNewNote(newNote);
// Quit the dialog
dismiss();
}
});
return builder.create();
}
}
>
public class DialogShowNote extends DialogFragment {
private Note mNote;
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Receive a note from the MainActivity
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_show_note, null);
TextView txtTitle = (TextView) dialogView.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) dialogView.findViewByI (R.id.tx tDescription);
txtTitle.setText(mNote.getTitle());
txtDescription.setText(mNote.getDescription());
ImageView ivImportant = (ImageView) dialogView.findViewById(R.id.imageViewImportant);
ImageView ivTodo = (ImageView) dialogView.findViewById(R.id.imageViewTodo);
ImageView ivIdea = (ImageView) dialogView.findViewById(R.id.imageViewIdea);
if (!mNote.isImportant()) {
ivImportant.setVisibility(View.GONE);
}
if (!mNote.isTodo()) {
ivTodo.setVisibility(View.GONE);
}
if (!mNote.isIdea()) {
ivIdea.setVisibility(View.GONE);
}
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView).setMessage("Your Note");
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return builder.create();
}
public void sendNoteSelected(Note noteSelected) {
mNote = noteSelected;
}
}
public class MainActivity extends AppCompatActivity {
// Temporary code
Note mTempNote = new Note();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Temporary code
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create a new DialogShowNote called dialog
DialogShowNote dialog = new DialogShowNote();
// Send the note via the sendNoteSelected method
dialog.sendNoteSelected(mTempNote);
// Create the dialog
dialog.show(getFragmentManager(), "123");
}
});
}
public void createNewNote(Note n){
// Create a mNote
mTempNote = n;
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_add) {
DialogNewNote dialog = new DialogNewNote();
dialog.show(getFragmentManager(), "");
return true;
}
return super.onOptionsItemSelected(item);
}
}
5-16 15:32:20.654 2673-2673/com.example.melisa.notetoself W/System: ClassLoader referenced unknown path: /data/app/com.example.melisa.notetoself-2/lib/x86
05-16 15:32:20.934 2673-2673/com.example.melisa.notetoself W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
05-16 15:32:20.975 2673-2741/com.example.melisa.notetoself D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
05-16 15:32:21.042 2673-2741/com.example.melisa.notetoself I/OpenGLRenderer: Initialized EGL, version 1.4
05-16 15:32:23.438 2673-2741/com.example.melisa.notetoself E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae3f2e30

android radiobutton button accept

I have a problem with button Set Color. Set Color is to activate the selected RadioButton. For example, selecting the first radiobutton and when you click "Set Color" is the background color change to red. Here is my Android Studio codes.
UPDATE
My app working process now:
When I click for example on first RadioButton my textview background color change automatically. Its skipping my "Set Color" button.
My intended app working.
When I click for example on first RadioButton and after that I accept my choose clicking "Set Color" button my textview background color change.
XML file
<LinearLayout 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:layout_centerHorizontal="true"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:checkedButton="#+id/czerwonyguzik"
android:gravity="center_horizontal"
android:orientation="horizontal">
<RadioButton
android:id="#+id/czerwonyguzik"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/Czerwony"
android:onClick="onRadioClicked" />
<RadioButton
android:id="#+id/bialyguzik"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/White"
android:onClick="onRadioClicked" />
<RadioButton
android:id="#+id/niebieskiguzik"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/Niebieski"
android:onClick="onRadioClicked" />
</RadioGroup>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal">
<Button
android:id="#+id/setcolor"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Set Color" />
<Button
android:id="#+id/cancel"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:onClick="anulacjaopcji"
android:text="Anuluj" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textwju"
android:layout_width="match_parent"
android:layout_height="101dp"
android:background="#color/red"
android:textColor="#color/White" />
</LinearLayout>
</LinearLayout>
JAVA file
public class LinearLayout extends ActionBarActivity {
RadioGroup rg;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear_layout);
TextView textView = (TextView) findViewById(R.id.textwju);
rg = (RadioGroup) findViewById(R.id.radioGroup);
}
public void onRadioClicked(View view) {
textView = (TextView) findViewById(R.id.textwju);
// czy guzik jest wcisniety
boolean wcisniety = ((RadioButton) view).isChecked();
//sprawdzenie ktory guzik jest wcisniety
switch (view.getId()) {
case R.id.czerwonyguzik:
if (wcisniety)
textView.setBackgroundColor(getResources().getColor(R.color.Czerwony));
break;
case R.id.bialyguzik:
if (wcisniety)
textView.setBackgroundColor(getResources().getColor(R.color.White));
break;
case R.id.niebieskiguzik:
if (wcisniety)
textView.setBackgroundColor(getResources().getColor(R.color.Niebieski));
break;
}
}
public void anulacjaopcji(View view) {
rg.check(R.id.czerwonyguzik);
textView.setBackgroundColor(getResources().getColor(R.color.Czerwony));
}
#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_radio_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try the following
RadioButton radioButton1, radioButton2, radioButton3;
Button setColorButton, cancelButton;
TextView textwju;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radiobutton_example);
radioButton1 = (RadioButton) findViewById(R.id.czerwonyguzik);
radioButton2 = (RadioButton) findViewById(R.id.bialyguzik);
radioButton3 = (RadioButton) findViewById(R.id.niebieskiguzik);
setColorButton = (Button) findViewById(R.id.setcolor);
cancelButton = (Button) findViewById(R.id.cancel);
textwju = (TextView) findViewById(R.id.textwju);
setColorButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(radioButton1.isChecked()) {
textwju.setBackgroundColor(getResources().getColor(R.color.blue));
} else if(radioButton2.isChecked()) {
textwju.setBackgroundColor(getResources().getColor(R.color.white));
} else if(radioButton3.isChecked()) {
textwju.setBackgroundColor(getResources().getColor(R.color.red));
}
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioButton1.setChecked(true);
}
});
}
And don't forget to remove android:onClick="onRadioClicked" from the radio buttons in the xml.
Create field for saving textview color in, and just save in it new value on onRadioClicked. After you click your "Set Color" call your textView.setBackgroundColor(savedColor).
you can get the option selected by
int radioButtonID = group.getCheckedRadioButtonId();
View radioButton = group.findViewById(radioButtonID);
int radioId = group.indexOfChild(radioButton);
String optionText =
(RadioButton)group.getChildAt(radioId)).getText().toString();
now you can do what ever you want
hope this helps

Function is not getting called with the button in Android

I'm trying to make my first Android application, and here is the problem i met:
When i am tapping the Yes Button, the function onYesButtonClick() is not called. The function is supposed to change the visibility of the TextView with the id TextView1, but when i tap, nothing happens. Here is the activity_main.xml:
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="#string/q1" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:text="#string/hello_world"
android:visibility="invisible" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView01"
android:layout_marginTop="22dp"
android:layout_toLeftOf="#+id/textView1"
android:onClick="onYesButtonClick"
android:text="Yes" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_toRightOf="#+id/textView1"
android:onClick="onNoButtonClick"
android:text="No" />
and here is the MainActivity.java:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onYesButtonClick(View view){
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setVisibility(android.view.View.VISIBLE);
}
public void onNoButtonClick(View view){
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
declare textView in onCreate method because findViewById available in context of activity methods. So Change your code as
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.textView1);
}
public void onYesButtonClick(View view){
textView.setVisibility(android.view.View.VISIBLE);
}
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onYesButtonClick(View view){
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setVisibility(View.VISIBLE);
}
public void onNoButtonClick(View view){
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setVisibility(View.GONE);
}
}
//this should be in your onCreate methord
TextView textView = (TextView) findViewById(R.id.textView1);
public void onYesButtonClick(View view){
if(view.getID()==R.id.button1){
textView.setVisibility(android.view.View.VISIBLE);
}
}

How to add a reset button to clear numbers on Edittext field

I want to add a button to clear the numbers on textfield by tapping on the button.
(Reset my EditText back to an empty "space" after a button has pressed that would have completed an activity with input from the EditText field.)
Cheers! Thanks!
ActivityMain XML file!
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/back"
android:orientation="vertical"
tools:context="com.miuapps.unitconverter.Centimetres_Metres" >
<TextView
android:id="#+id/textView1" //first textview
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter a Value(cm) :"
android:layout_gravity="center"
android:gravity="center"
android:textSize="30dp"/>
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Convert" />
<TextView
android:id="#+id/tvDisplay1" //output textview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="In Metres: 0"
android:textSize="30dp" />
</LinearLayout>
double counter, counter2 = 100;
double x;
Button conv;
TextView dis1, dis2;
EditText ent1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
conv = (Button)findViewById(R.id.button1);
dis1 = (TextView)findViewById(R.id.tvDisplay1);
//dis2 = (TextView)findViewById(R.id.tvDisplay2);
ent1 = (EditText)findViewById(R.id.editText1);
conv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
x = new Integer(ent1.getText().toString());
counter = x/100;
//counter2++;
dis1.setText("In Metres: " +counter);
//dis2.setText("In Centimetres: " +counter2);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
How about this:
ent1.setText("");
just put it at the end of your onClick Method
Edit:
conv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// here you get the text from your editText
x = new Integer(ent1.getText().toString());
// do something with the text
counter = x/100;
// set result in another TextView
dis1.setText("In Metres: " +counter);
// work is done, so the editText can be cleared
ent1.setText("");
}
});
Edit 2 (reset button):
resetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// reset only by another button
ent1.setText("");
}
});
Simply add a button in your layout.
<Button
android:id="#+id/buttonReset"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Reset" />
Find that button in your activity:
Button mButtonReset = (Button) findViewById(R.id.buttonReset);
mButtonReset.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view){
ent1.setText("");
}
});
First Create Design,
Activity_main.xml like below,
<EditText
android:id="#+id/txt_1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:ems="10"
android:hint="Enter Name"
android:inputType="textPersonName"
android:minHeight="48dp" />
<Button
android:id="#+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Button" />
<Button
android:id="#+id/btn_cln"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Clear" />
**Then go to MainActivity.java edit code like below, **
**
public class MainActivity extends AppCompatActivity {
Button button,button2;
EditText editText;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn_ok);
editText = findViewById(R.id.txt_1);
button2 = findViewById(R.id.btn_cln);
//create text add button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = editText.getText().toString();
}
});
//clean,reset text button
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText.setText("");
}
});
}
}
**

Categories

Resources