I want to create dynamic RadioGroup (with dynamic radio options). I'm doing with the following code.
My question is that, how can I get the option that is selected by clicking the button "Check Answer". If the radio group is added through the XML layout then I can get by its ID, but in this case I'm unable to do so.
Here's the code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="#+id/button">
</LinearLayout>
<TextView
android:id="#+id/answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/button"
android:textColor="#008b00"
/>
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check Answer"
app:layout_constraintBottom_toBottomOf="parent"
android:onClick="checkAnswer"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity:
package com.example.quiz8;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private LinearLayout linearLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option...");
}
}
You can set a tag to the RadioGroup in order to be able to find it easily. A tag can be any Object. We'll use a String here, which has to be unique in the ViewGroup on which you call findViewWithTag(). Then in checkAnswer() you retrieve the RadioGroup by its tag and so get the text of the checked RadioButton.
private static final String RADIOGROUP_TAG = "radiogroup";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setTag(RADIOGROUP_TAG);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
RadioGroup radioGroup = linearLayout.findViewWithTag(RADIOGROUP_TAG);
int checkedId = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = radioGroup.findViewById(checkedId);
String text = radioButton.getText().toString();
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option..." + text);
}
Another option: you can have String[] title and the RadioGroup as fields in your Activity. This makes sense since you need them in more than one place.
private final String[] title = {"Male", "Female", "Other", "Secret"};
private RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
radioGroup = new RadioGroup(this);
RadioButton radioButton;
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
int checkedId = radioGroup.getCheckedRadioButtonId();
TextView answerText = (TextView) findViewById(R.id.answer);
// Note: make sure there is a checked RadioButton!
answerText.setText("You selected the option..." + title[checkedId]);
}
You can simply check for the selected one.
public class MainActivity extends AppCompatActivity {
private LinearLayout linearLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//checkedId is the RadioButton selected
}
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option...");
}
}
1) You can add following code in OnClickListner() to check if desired check boxed is clicked.
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
Further help can be found in Radio button documentation : Radio Button Documentation
2) Another method: A better way is to use RadioGroup and set the listener on this to change and update the View accordingly (saves you having 2 or 3 or 4 etc listeners).
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
}
});
Related
I need to pass one parameter from one Java class(A) to another Java class(B).
I use many solutions from the Internet but it couldn't solve my problem. The user will choose their answer from a list of radio button. The score will be added and I need to pass the score to B class.
In B class, the user continues to answer the question and I need to add the score from both A and B class to get the final score and display it at the bottom of B class. The application keep stopped when I click on the button in A class. But I think the problem is in B class. Does anyone know how to solve this? Thank you so much.
A class
private int score;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
Button btn = findViewById(R.id.anxnext);
final RadioGroup rg1 = findViewById(R.id.anxq1g);
final RadioGroup rg2 = findViewById(R.id.anxq2g);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get the checked Radio Button ID from Radio Group
int g1 = rg1.getCheckedRadioButtonId();
int g2 = rg2.getCheckedRadioButtonId();
if (g1 != -1) {
View radioButton = rg1.findViewById(g1);
idx1 = rg1.indexOfChild(radioButton);
}
if (g2 != -1) {
View radioButton = rg2.findViewById(g2);
idx2 = rg2.indexOfChild(radioButton);
}
score=idx1+idx2;
Intent intent = new Intent(A.this, B.class);
intent.putExtra("message", score);
startActivity(intent);
}
});
}
B class
private int score1,totalscore;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b);
Bundle extras = getIntent().getExtras();
if(extras!=null) {
String m= extras.getString("message");
totalscore=Integer.parseInt(m);
}
Button btn = findViewById(R.id.anxresult);
final TextView tv_result = findViewById(R.id.tv_result);
final RadioGroup rg10 = findViewById(R.id.anxq10g);
final RadioGroup rg11 = findViewById(R.id.anxq11g);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get the checked Radio Button ID from Radio Grou[
int g1 = rg10.getCheckedRadioButtonId();
int g2 = rg11.getCheckedRadioButtonId();
if (g1 != -1) {
View radioButton = rg10.findViewById(g1);
idx10 = rg10.indexOfChild(radioButton);
}
if (g2 != -1) {
View radioButton = rg11.findViewById(g2);
idx11 = rg11.indexOfChild(radioButton);
}
score1 = idx10 + idx11;
totalscore = score1 + totalscore;
tv_result.setText(totalscore + " selected.");
}
});
}
Below showed in the logcat
Take care of the data type:
In A class, you have:
score=idx1+idx2;
Intent intent = new Intent(A.this, B.class);
intent.putExtra("message", score);
startActivity(intent);
which score is int, however in B class:
Bundle extras = getIntent().getExtras();
if(extras!=null) {
String m= extras.getString("message");
totalscore=Integer.parseInt(m);
}
You are trying to get it as a String, and it is null so the app crashes.
So please change it to:
Bundle extras = getIntent().getExtras();
if(extras!=null) {
totalscore = extras.getInt("message");
}
And try again
try like this example
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_male"
android:checked="true" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_female" />
</RadioGroup>
In your class A
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
});
post the crash report to know more about your issue
I am working on an application where I need to create a list. The list contains 2 textViews and 1 checkbox. The list has to delete the row which detects a click on it. But the click will only be detected when the checkbox's focusability is set to false. But the aim of the application is to also delete the row when the respective checkbox is checked.
But the onItemClickListener does not detect the click on the checkbox.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
ArrayList<ListData> ListData = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting");
final ListDataAdapter adapter = new ListDataAdapter(this ,R.layout.list_layout,ListData );
Button button= (Button) findViewById(R.id.Button);
CheckBox checkBox =(CheckBox)findViewById(R.id.checkbox);
final ListView listView = (ListView)findViewById(R.id.ListView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView textView1 = (TextView) findViewById(R.id.TextView1);
TextView textView2 = (TextView) findViewById(R.id.TextView2);
EditText editText1 = (EditText) findViewById(R.id.EditText1);
EditText editText2 = (EditText) findViewById(R.id.EditText2);
if (editText1.getText() != null && editText2!=null) {
String title = editText1.getText().toString();
String description = editText2.getText().toString();
textView1.setText(title);
textView2.setText(description);
ListData data = new ListData(title, description);
ListData.add(data);
saveArrayList();
Log.i(TAG, "display:" + ListData);
adapter.notifyDataSetChanged();
editText1.setText("");
editText2.setText("");
listView.setAdapter(adapter);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d(TAG, "onItemClick: tapped");
ListData.remove(i);
saveArrayList();
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
return true;
}
});
}
}
The XML file is
<CheckBox
android:id="#+id/checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="90"
android:focusable="false"
android:focusedByDefault="false" />
I have a navigation activity consisting of fragments. The app is, currently, made to take the selected Id from the radiogroup and display it's text as a toast on a click of a button. But the app only display's the radiobutton that is already checked (Defined in xml), if I change the radiobutton that is selected, it will still show the one that was checked as defined in the xml
This is the java class (FirstFragment.java)
public class FirstFragment extends Fragment implements View.OnClickListener {
View myView;
private RadioGroup radioGroup;
private RadioButton radioButton;
Button btnDisplay;
String text;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.first_layout, container, false);
btnDisplay = (Button) myView.findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(this);
radioGroup = (RadioGroup) myView.findViewById(R.id.radio);
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) myView.findViewById(selectedId);
return myView;
}
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),
text = radioButton.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
And this is the xml file
<RadioGroup
android:id="#+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="89dp">
<RadioButton
android:id="#+id/radioGram"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:text="Gram"/>
<RadioButton
android:id="#+id/radioKilogram"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kilogram"
android:textSize="16sp"
android:checked="true"/>
</RadioGroup>
So, in this case, the toast would show "Kilogram", but if I check the "Gram" radiobutton, the toast would still show "Kilogram". Could anyone help fix this? Thank you
try this:
private RadioButton rb_1, rb_2;
//in on createView
rb_1 = (RadioButton) myView.findViewById(R.id.radioGram);
rb_2 = (RadioButton) myView.findViewById(R.id.radioKilogram);
rb_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),
rb1.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
rb_2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),
rb2.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
Alternative way: write this in onCreateView() after you have initilized myView
View myView = inflater.inflate(R.layout.first_layout, container, false);
RadioGroup radioGroup = (RadioGroup) myView.findViewById(R.id.radio);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
switch(checkedId){
case R.id.radioGram:
// do operations specific to this selection
Toast.makeText(getActivity(),"Gram selected", Toast.LENGTH_SHORT).show();
break;
case R.id.radioKilogram:
// do operations specific to this selection
Toast.makeText(getActivity(),"KiloGram selected", Toast.LENGTH_SHORT).show();
break;
}
}
});
You are calling
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) myView.findViewById(selectedId);
inside onCreateView which is calling only once. Because of that every time same value getting displayed on toast. Try to get value inside onClick:
public class FirstFragment extends Fragment implements View.OnClickListener {
View myView;
private RadioGroup radioGroup;
private RadioButton radioButton;
Button btnDisplay;
String text;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.first_layout, container, false);
btnDisplay = (Button) myView.findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(this);
radioGroup = (RadioGroup) myView.findViewById(R.id.radio);
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) myView.findViewById(selectedId);
return myView;
}
#Override
public void onClick(View v) {
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) myView.findViewById(selectedId);
Toast.makeText(getActivity(),
text = radioButton.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
I have 6 buttons and I'm trying to shuffle their position when any button is clicked.
The first shuffle (when the activity is started) is done by: Collections.shuffle(buttonList);
How do I shuffle when any of the buttons is clicked?
Java:
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
LinearLayout ll = (LinearLayout) findViewById(R.id.llShuffleBox);
LinearLayout top_layout = (LinearLayout) findViewById(R.id.top_layout);
LinearLayout middle_layout = (LinearLayout) findViewById(R.id.middle_layout);
final ArrayList<Button> buttonList = new ArrayList<Button>();
for(int i=0; i<6; i++) {
final Button b = new Button(this);
b.setText("" + (i + 1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setId(i + 1);
buttonList.add(b);
}
//First shuffle
Collections.shuffle(buttonList);
for (int i = 0; i<6; i++) {
if (i <3) {
top_layout.addView(buttonList.get(i));
} else {
middle_layout.addView(buttonList.get(i));
}
}
}
}
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Main">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llShuffleBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="50dp">
<LinearLayout
android:id="#+id/top_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
</LinearLayout>
<LinearLayout
android:id="#+id/middle_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
First move the initial setup of the buttons to the onCreate method.
private LinearLayout top_layout;
private LinearLayout middle_layout;
private final ArrayList<Button> buttonList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
top_layout = (LinearLayout) findViewById(R.id.top_layout);
middle_layout = (LinearLayout) findViewById(R.id.middle_layout);
for(int i=0; i<6; i++) {
final Button b = new Button(this);
b.setText("" + (i + 1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setId(i + 1);
b.setOnClickListener(clickListener);
buttonList.add(b);
}
shuffleButtons();
}
Then put the code to remove button views, shuffle them, then re-add in a method.
private void shuffleButtons() {
top_layout.removeAllViews();
middle_layout.removeAllViews();
Collections.shuffle(buttonList);
for (int i = 0; i<6; i++) {
if (i <3) {
top_layout.addView(buttonList.get(i))
} else {
middle_layout.addView(buttonList.get(i));
}
}
}
Also attach a click listener to each of the buttons that will call through to the shuffle method.
private View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
shuffleButtons();
}
}
Consider: Instead of shuffling the buttons change the numbers on them, that way you don't have to re-layout your app and move the buttons around.
If you are set on shuffling the buttons the easiest way is to remove them and add them back in the new order.
To get the event when you click on a button you register an onClickListener, the code for that could look like this:
class YourClass implements OnClickListener
final Button b = new Button(this);
b.setText("" + (i + 1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setOnClickListener (this)
public void onClick(View view) {
shuffle();
}
Try something like this
public class Main extends AppCompatActivity implements OnClickListener{
private Button b1, b2, b3, b4, b5, b6;
private ArrayList<Button> buttonList = new ArrayList<Button>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i=0; i<6; i++) {
final Button b = new Button(this);
b.setText("" + (i + 1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setId(i + 1);
buttonList.add(b);
}
b1 = (Button) findViewById(...);
b2 = (Button) findViewById(...);
b3 = (Button) findViewById(...);
b4 = (Button) findViewById(...);
b5 = (Button) findViewById(...);
b6 = (Button) findViewById(...);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
LinearLayout ll = (LinearLayout) findViewById(R.id.llShuffleBox);
LinearLayout top_layout = (LinearLayout) findViewById(R.id.top_layout);
LinearLayout middle_layout = (LinearLayout) findViewById(R.id.middle_layout);
//First shuffle
Collections.shuffle(buttonList);
for (int i = 0; i<6; i++) {
if (i <3) {
top_layout.addView(buttonList.get(i));
} else {
middle_layout.addView(buttonList.get(i));
}
}
}
#Override
public void onClick(View v) {
Collections.shuffle(buttonList);
}
}
Replace the ... for their respective layout ids.
Just after b.setId(i+1); add this code -
b.setId(i + 1); //this line you already have add these after
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(buttonList);
for (int i=0; i<6; i++){
//removing the buttons from the view
ViewGroup layout = (ViewGroup) buttonList.get(i).getParent();
if (null != layout) //for safety only as you are doing onClick
layout.removeView(buttonList.get(i));
}
for (int i = 0; i<6; i++) {
//adding the buttons again
if (i <3) {
top_layout.addView(buttonList.get(i));
} else {
middle_layout.addView(buttonList.get(i));
}
}
}
});//end of onClickListener; this is all which you have to add;
buttonList.add(b);//this line you already have
}
This is all. It should do exactly what you want now.
I've built an Android application that programmatically creates a textview and an edittext on the UI when the user presses a button. Currently when you press the 'add' button the two fields are created but the edittext appears underneith the textview, i'd like the edittext to appear on screen aligned to the right of the textview like so:
[addbutton]
[textview][edittext]
[textview][edittext]
[textview][edittext]
code:
private OnClickListener addForm() {
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout.addView(createNewTextView(numberString));
mLayout.addView(createNewEditText(null));
numberInt = Integer.parseInt(numberString);
numberInt++;
numberString = Integer.toString(numberInt);
}
};
}
// add textview
private TextView createNewTextView(String text) {
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText(text);
return textView;
}
// add edittext
private EditText createNewEditText(String text) {
final EditText editText = new EditText(this);
editText.setLayoutParams(lparams);
editText.setText(text);
return editText;
}
REVISION 1:
OK so I've changed my code around a bit to what I think should work but the edittext is still appearing below, can anyone see where i'm going wrong or change my code around to make it work?
New code:
private OnClickListener add() {
return new OnClickListener() {
#Override
public void onClick(View v) {
createNewTextView(numberString);
numberInt = Integer.parseInt(numberString);
numberInt++;
numberString = Integer.toString(numberInt);
}
};
}
// add textview
private void createNewTextView(String text) {
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText(text);
textView.setId(numberInt);
mLayout.addView(textView);
createNewEditText(textView);
}
// add edittext
private void createNewEditText(TextView textView) {
final EditText editText = new EditText(this);
lparams.addRule(RelativeLayout.RIGHT_OF, textView.getId());
editText.setLayoutParams(lparams);
mLayout.addView(editText);
}
REVISION 2:
All java and XML code below:
Java:
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private LinearLayout mLayout;
private Button mButton;
private String numberString = "1";
private int numberInt = 1;
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(add());
TextView textView = new TextView(this);
textView.setText("New text");
}
private OnClickListener add() {
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout.addView(createNewTextView(numberString));
mLayout.addView(createNewEditText(null));
numberInt = Integer.parseInt(numberString);
numberInt++;
numberString = Integer.toString(numberInt);
}
};
}
// add textview
private TextView createNewTextView(String text) {
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText(text);
return textView;
}
// add edittext
private EditText createNewEditText(String text) {
final EditText editText = new EditText(this);
editText.setLayoutParams(lparams);
editText.setText(text);
editText.setId(numberInt);
int i = editText.getId();
Toast toast= Toast.makeText(MainActivity.this,"edittext ID:" + i , Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
return editText;
}
}
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/linearLayout">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add+"
/>
</LinearLayout>
Set id to the TextView and EditText then use RelativeLayout LayoutParams to align right or left using rules like params.addRule(RelativeLayout.ALIGN_LEFT,id);
If your main layout is LinearLayout then make Sure that your main layout orientation is horizontal...and use below code
LayoutParams lparams= new RelativeLayout.LayoutParams(new ViewGroup.MarginLayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("TextView");
textView.setId(1);
mLayout.addView(textView);
EditText editText = new EditText(this);
lparams.addRule(RelativeLayout.ALIGN_RIGHT, textView.getId());
editText.setLayoutParams(lparams);
mLayout.addView(editText);
Use RelativLayout and set Rule like android:layout_toRightOf="#+id/textview"
Use the relative layout as a container and Use relative layout params to align edittext and textview. In the relative layout params there are alignright,alignleft etc.. as in xml.
developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html