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
Related
<ImageView
android:id="#+id/ivPopup"
android:layout_width="wrap_content"
android:layout_height="35dp"
app:srcCompat="#drawable/logout"
android:layout_marginStart="144dp"
android:layout_alignParentTop="true"`enter code here`
android:layout_toEndOf="#+id/tvProfileName"
android:layout_marginTop="2dp"
/>
Here is the java code to refer the ImageView
final ImageView ivPopup = (ImageView) findViewById(R.id.ivPopup);
For some reason, the android cannot resolve the ivPopup in R.id.ivPopup
Main Activity
public class HomePage extends AppCompatActivity implements View.OnClickListener {
private static final String TAG ="Menu";
private FirebaseAuth mAuth;
private ImageView ivPopup;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
TextView tvProfile = (TextView) findViewById(R.id.tvProfile);
tvProfile.setOnClickListener(this);
Button btnNotes = (Button) findViewById(R.id.btnNotes);
btnNotes.setOnClickListener(this);
Button btnTimeTable = (Button) findViewById(R.id.btnTimeTable);
btnTimeTable.setOnClickListener(this);
Button btnClass = (Button) findViewById(R.id.btnClass);
btnClass.setOnClickListener(this);
TextView tvProfileName = (TextView) findViewById(R.id.tvProfileName);
// Bundle extras =getIntent().getExtras();
// String user1 = extras.getString("username");
mAuth = FirebaseAuth.getInstance();
ivPopup = (ImageView) findViewById(R.id.ivPopup);
ivPopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(HomePage.this,ivPopup);
popupMenu.getMenuInflater().inflate(R.menu.menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(HomePage.this,"" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popupMenu.show();
}
Clean code
Rebuild code
Try to Invalidate Caches & Restart.
if It's still not working then change your id from ivPopup to something else in XML as well as JAVA
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
}
});
I made the close button on the inflated layer. And I want to close this inflated layer when I click that button. How can I solve this problem
I used Rl.setVisibility(View.GONE);
But When I restart this method it's not working properly.
(different layer comes out...all the buttons are not working)
public void layer(){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final RelativeLayout Rl = (RelativeLayout) inflater.inflate(R.layout.menu_bookmark, null);
//Rl.setBackgroundColor(Color.parseColor("#99000000"));
final RelativeLayout.LayoutParams paramRl = new RelativeLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, WRAP_CONTENT);
addContentView(Rl, paramRl);
final String current_url = webView.getUrl();
final Button btn_add = (Button) findViewById(R.id.btn_add);
final Button btn_out = (Button) findViewById(R.id.btn_out);
final EditText editText = (EditText) findViewById(R.id.edit_input);
editText.setText(current_url);
final ListView listView = (ListView) findViewById(R.id.lv_bookmark);
final ArrayList<String> arrayList = new ArrayList<String>();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.menu_bookmark_row, arrayList);
listView.setAdapter(arrayAdapter);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText.getText().toString().length() > 0) {
String inputStr = editText.getText().toString();
arrayList.add(inputStr);
arrayAdapter.notifyDataSetChanged();
}
}
});
btn_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// <--I NEED HELP!!!!!
}
});
parentLinearLayout.removeView((View) v.getParent());
https://www.androidtutorialpoint.com/basics/dynamically-add-and-remove-views-in-android/
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" />
intent.putExtra ( "result", (double) kg / (Math.pow (tall, 2)) / 10000);// <SecondActivity>
result = intent.getDoubleExtra double ("result", 0); //<ThirdActivity>
I have tried the following:
tall: 150 cm
kg: 50kg
result: 1.95 .... (original calculations. 19.5)
Even if the value does not appear 10 Multiply.
★ float cast upon the results will not come.
The problem occurs after fertilization in the post.
Android Studio with intent to other activities
(original code)
[SecondActivity]
public class SecondActivity extends Activity {
RadioGroup rg;
ImageButton button4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
rg = (RadioGroup) findViewById(R.id.radioGroup);
button4 = (ImageButton) findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton rd = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
//String str_Qtype = rd.getText().toString();
EditText et1 = (EditText) findViewById(R.id.EditText02); // tall (inot typing error)
EditText et2 = (EditText) findViewById(R.id.EditText01); // kg (not typing error)
int tall = Integer.parseInt(et1.getText().toString());
int kg = Integer.parseInt(et2.getText().toString());
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
intent.putExtra("tall", Integer.parseInt(et1.getText().toString()));
intent.putExtra("kg", Integer.parseInt(et2.getText().toString()));
intent.putExtra("result",(double)kg/(Math.pow(tall,2))/10000);
startActivity(intent);
}
});
}
}
[ThridActivity]
package com.example.bmi_calculate;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class ThirdActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
Intent intent = getIntent();
int tall = intent.getIntExtra("tall", 0);
int kg = intent.getIntExtra("kg", 0);
double result = intent.getDoubleExtra("result",0);
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
TextView tv3 = (TextView)findViewById(R.id.textView3);
tv1.setText("" + tall);
tv2.setText("" + kg);
tv3.setText(""+String.valueOf(result));
}
}
In your second activity you are storing your results in variables tall and kg create a third variable result and pass that variable to the method
#Override
public void onClick(View v) {
RadioButton rd = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
//String str_Qtype = rd.getText().toString();
EditText et1 = (EditText) findViewById(R.id.EditText02); // tall (inot typing error)
EditText et2 = (EditText) findViewById(R.id.EditText01); // kg (not typing error)
int tall = Integer.parseInt(et1.getText().toString());
int kg = Integer.parseInt(et2.getText().toString());
float result = kg/(tall*0.1)*(tall*0.1))
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
intent.putExtra("tall", tall);
intent.putExtra("kg", kg);
intent.putExtra("result",result);
startActivity(intent);
and in third activity
float result = intent.getFloatExtra("result",0);
To save the value, do this:
intent.putExtra("result",(float) (kg/((tall*0.01)*(tall*0.01))) ); // tall in cm unit
You need to get float value or save as int:
float result = intent.getFloatExtra("result", 0f);
[Edit] - fixed code typo