in my app i cant use XML layout for some reason now i need to create a layout which its XML code is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/adlayout"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="vertical" >
<ir.adad.AdView
android:id="#+id/ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
token="fhsfxfhdghghrgfggh" />
</LinearLayout>
now i need to create a java code which its the same as this XML code! is there any way?how i can do this?
i:ir.adad.adview is a ad services and i put its liberally in my app.
This might help you a bit.
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
int adlayout = 12345; //if you need id of layout somewhere else
//View.generateViewId();Can be used if minSDK= 17
layout.setId(adlayout);
android.view.ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = 48;
params.width = LayoutParams.MATCH_PARENT;
//Below code is used if you need height in dp.
//int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());
ir.adad.AdView adView = new ir.adad.AdView(this);
int adViewId = 123456;//Should not be dublicate.
adView.setId(adViewId);
android.view.ViewGroup.LayoutParams paramView = adView.getLayoutParams();
paramView.height = LayoutParams.WRAP_CONTENT;
paramView.width = LayoutParams.WRAP_CONTENT;
layout.addView(adView)
Since I don't know that ad service library I can't help you with its constructor and creation but this should give you something to start working on.
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,48);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(params);
ir.adad.AdView adview = new ir.adad.AdView();
LinearLayout.LayoutParams adviewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
adview.setLayoutParams(params);
adview.setToken("asdasdas");
layout.addView(adview);
Related
I'm trying to add two text views to a LinearLayout programmatically (in a loop), and then in turn adding that to a LinearLayout that's defined in the layout file. The code runs with no errors, and when evaluating getChildCount I get the expected value, but absolutely nothing is rendering on the device.
XML:
<LinearLayout
android:id="#+id/llNotes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:layout_marginLeft="1dp"
android:layout_marginEnd="1dp"
android:layout_marginRight="1dp"
android:layout_marginBottom="#dimen/activity_vertical_margin_quarter"
android:background="#drawable/rounded_bottom_corners"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin_half"
android:paddingBottom="#dimen/activity_vertical_margin" />
Java:
for (Note MyNote : foo.GetNotes()) {
LinearLayout llNoteParent = new LinearLayout(this);
TextView tvNoteHeader = new TextView(this);
TextView tvNoteValue = new TextView(this);
LinearLayout.LayoutParams llParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llParams.gravity = Gravity.CENTER_HORIZONTAL;
llNoteParent.setLayoutParams(llParams);
llNoteParent.setOrientation(LinearLayout.HORIZONTAL);
llNoteParent.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
llNoteParent.setPadding(R.dimen.activity_horizontal_margin, R.dimen.activity_vertical_margin_half, R.dimen.activity_horizontal_margin, R.dimen.activity_horizontal_margin);
LinearLayout.LayoutParams tvNoteHeaderParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
tvNoteHeaderParams.weight = 1;
tvNoteHeader.setLayoutParams(tvNoteHeaderParams);
tvNoteHeader.setPadding(R.dimen.activity_vertical_margin_half, R.dimen.activity_vertical_margin_half, R.dimen.activity_vertical_margin_half, R.dimen.activity_vertical_margin_half);
tvNoteHeader.setBackground(getDrawable(R.drawable.left_text_field));
tvNoteHeader.setGravity(Gravity.CENTER);
tvNoteHeader.setText(MyNote.GetAbbreviatedText());
LinearLayout.LayoutParams tvNoteValueParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
tvNoteValueParams.weight = 1;
tvNoteValue.setLayoutParams(tvNoteValueParams);
tvNoteValue.setPadding(R.dimen.activity_vertical_margin_half, R.dimen.activity_vertical_margin_half, R.dimen.activity_vertical_margin_half, R.dimen.activity_vertical_margin_half);
tvNoteValue.setBackground(getDrawable(R.drawable.right_text_field));
tvNoteValue.setText(MyNote.GetText());
llNoteParent.addView(tvNoteHeader);
llNoteParent.addView(tvNoteValue);
llNotes.addView(llNoteParent);
}
you cannot pass number with dp into setPadding method
setPadding(R.dimen.activity_horizontal_margin, R.dimen.activity_vertical_margin_half, R.dimen.activity_horizontal_margin, R.dimen.activity_horizontal_margin);
you need to pass integers into setPadding method.
1- try something like this
llNoteParent.setPadding(20,20,20,20);
tvNoteHeader.setPadding(20,20,20,20);
2- OR user integer.xml
for (Note MyNote : foo.GetNotes()) {
LinearLayout llNoteParent = new LinearLayout(this);
TextView tvNoteHeader = new TextView(this);
TextView tvNoteValue = new TextView(this);
LinearLayout.LayoutParams llParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llParams.gravity = Gravity.CENTER_HORIZONTAL;
llNoteParent.setLayoutParams(llParams);
llNoteParent.setOrientation(LinearLayout.HORIZONTAL);
llNoteParent.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
llNoteParent.setPadding(R.integer.activity_horizontal_margin, R.integer.activity_vertical_margin_half, R.integer.activity_horizontal_margin, R.integer.activity_horizontal_margin);
LinearLayout.LayoutParams tvNoteHeaderParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
tvNoteHeaderParams.weight = 1;
tvNoteHeader.setLayoutParams(tvNoteHeaderParams);
tvNoteHeader.setPadding(R.integer.activity_vertical_margin_half, R.integer.activity_vertical_margin_half, R.integer.activity_vertical_margin_half, R.integer.activity_vertical_margin_half);
tvNoteHeader.setBackground(getDrawable(R.drawable.left_text_field));
tvNoteHeader.setGravity(Gravity.CENTER);
tvNoteHeader.setText(MyNote.GetAbbreviatedText());
LinearLayout.LayoutParams tvNoteValueParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
tvNoteValueParams.weight = 1;
tvNoteValue.setLayoutParams(tvNoteValueParams);
tvNoteValue.setPadding(R.integer.activity_vertical_margin_half, R.integer.activity_vertical_margin_half, R.integer.activity_vertical_margin_half, R.integer.activity_vertical_margin_half);
tvNoteValue.setBackground(getDrawable(R.drawable.right_text_field));
tvNoteValue.setText(MyNote.GetText());
llNoteParent.addView(tvNoteHeader);
llNoteParent.addView(tvNoteValue);
llNotes.addView(llNoteParent);
}
NOTE: Add the values to integer.xml file in values.
You have to use,
float horizontalMargin = getResources()
.getDimension(R.dimen.R.dimen.activity_horizontal_margin);
float verticleMargin = getResources()
.getDimension(R.dimen.R.dimen.activity_vertical_margin_half);
After that set padding,
llNoteParent.setPadding(horizontalMargin,verticleMargin, horizontalMargin, horizontalMargin);
tvNoteHeader.setPadding(verticleMargin, verticleMargin, verticleMargin, verticleMargin);
tvNoteValue.setPadding(verticleMargin, verticleMargin, verticleMargin, verticleMargin);
I am trying to create a 3x4 grid of buttons using the following code:
public class Grid extends AppCompatActivity {
LinearLayout myLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_grid);
myLayout = (LinearLayout) findViewById(R.id.content_grid);
for (int i = 0; i < 3; i++) {
LinearLayout row = new LinearLayout(this);
LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
row.setLayoutParams(rowParams);
for (int j = 0; j < 4; j++) {
final Button btn = new Button(this);
LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btn.setLayoutParams(btnParams);
btn.setText(" " + (j + 1 + (i * 4)));
btn.setId(j + 1 + (i * 4));
row.addView(btn);
}
myLayout.addView(row);
}
setContentView(myLayout);;
}
}
This code works perfectly fine and creates the grid as I want it, however if I change the line
myLayout = (LinearLayout) findViewById(R.id.content_grid);
to
myLayout = new LinearLayout(this);
Then only the first row of the grid is produced, not the 2nd and 3rd. I want to know why this is happening?
Whether the line
setContentView(R.id.content_grid);
is there or not does not seem make a difference in the second case.
In addition my content_grid.xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_grid"
</LinearLayout>
By default LinearLayout set orientation horizontal. Try set orientation vertical to myLayout by one LayoutParams.
I am creating various textviews inside a linear layout (lay). I want that when the textview reach out of the screen then that textview automatically jump on the next line instead of out of the screen. I am a beginner in android and not getting how to achieve it.
Here is my code:
for (int i = 0; i < string.size(); i++) {
final TextView txt = new TextView(con);
txt.setText(string.get(i));
lay.addView(txt);
}
Try This
TextView txt = new TextView(context);
txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
private void populateViews(LinearLayout linearLayout, ArrayList<TextView> views, View extraView)
{
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float mWidth = displaymetrics.widthPixels;
extraView.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout.removeAllViews();
int maxWidth = (int) mWidth - extraView.getMeasuredWidth() - 10;
linearLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params;
LinearLayout newLL = new LinearLayout(mContext);
newLL.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
newLL.setGravity(Gravity.LEFT);
newLL.setOrientation(LinearLayout.HORIZONTAL);
int widthSoFar = 0;
for (int i = 0; i < views.size(); i++)
{
LinearLayout LL = new LinearLayout(mContext);
LL.setOrientation(LinearLayout.HORIZONTAL);
LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
LL.setLayoutParams(new ListView.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
views.get(i).measure(0, 0);
params = new LinearLayout.LayoutParams(views.get(i).getMeasuredWidth(), LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 2, 10, 2);
LL.addView(views.get(i), params);
LL.measure(0, 0);
widthSoFar += views.get(i).getMeasuredWidth();
if (widthSoFar >= maxWidth)
{
linearLayout.addView(newLL);
newLL = new LinearLayout(mContext);
newLL.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
newLL.setOrientation(LinearLayout.HORIZONTAL);
newLL.setGravity(Gravity.LEFT);
params = new LinearLayout.LayoutParams(LL.getMeasuredWidth(), LL.getMeasuredHeight());
newLL.addView(LL, params);
widthSoFar = LL.getMeasuredWidth();
}
else
{
newLL.addView(LL);
}
}
linearLayout.addView(newLL);
}
This method should be able to help you. I had made this method long back, so with a few modifications you should be able to use it. The first parameter is a LinearLayout which will be the base vertical linear layout which will act as the primary container for the views. The second parameter are the actual views you have to add. The third parameter in my case was an Image which I was using like a placeholder.
You can add like this also.
for (int i = 0; i < string.size(); i++) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = (View) inflater.inflate(
R.layout.Layout_Design, null);
TextView txt = (TextView) view.findViewById(R.id.some_text);
txt.setText("for runtime change");
layout.addView(view);
// layout is linear layout in my case.
}
Layout_Design:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="80dp"
android:layout_height="80dp" >
<RelativeLayout
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="5dp" >
<TextView
android:id="#+id/some_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SOme Text" />
</RelativeLayout>
</FrameLayout>
I have an AlertDialog in my app that contains an EditText field. This dialog needs to be generated programmatically and should match the way the EditTextPreference dialog looks that is displayed automatically by Android when a user edits text by touching an EditTextPreference. This all works, but the size of the EditText inserted programmatically is too wide and doesn't match the one displayed by the EditTextPreference when touched. The following two images show the problem.
EditText looks like this when added to the AlertDialog using setView():
But should look like this:
Here is the XML code in the XML responsible for the EditTextPreference:
<EditTextPreference
android:title="Enter Name"
android:key="name"
android:defaultValue=""
android:summary=""
android:inputType="textCapSentences|textMultiLine"
android:singleLine="false"
android:gravity="top|left"
android:lines="2"
android:minLines="1"
android:maxLines="2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
/>
And the Java code responsible for my dialog:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainActivity);
alertDialog.setTitle("Enter Date");
final EditText input = new EditText(mainActivity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
input.setGravity(android.view.Gravity.TOP|android.view.Gravity.LEFT);
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES|InputType.TYPE_TEXT_FLAG_MULTI_LINE);
input.setLines(1);
input.setMaxLines(1);
input.setText(lastDateValue);
alertDialog.setView(input);
You have to add a container before doing that, e.g LinearLayout
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainActivity);
alertDialog.setTitle("Enter Date");
LinearLayout container = new LinearLayout(this);
container.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
final EditText input = new EditText(mainActivity);
input.setLayoutParams(lp);
input.setGravity(android.view.Gravity.TOP|android.view.Gravity.LEFT);
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES|InputType.TYPE_TEXT_FLAG_MULTI_LINE);
input.setLines(1);
input.setMaxLines(1);
input.setText(lastDateValue);
container.addView(input, lp);
alertDialog.setView(container);
I hope it helps :)
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainActivity);
alertDialog.setTitle("Enter Date");
final EditText input = new EditText(mainActivity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
input.setLayoutParams(lp);
input.setGravity(android.view.Gravity.TOP|android.view.Gravity.LEFT);
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES|InputType.TYPE_TEXT_FLAG_MULTI_LINE);
input.setLines(1);
input.setMaxLines(1);
input.setText(lastDateValue);
alertDialog.setView(input);
Please change your code as above and provide desire all margins
You can do this without extra container layout, only add this to your alertDialog :
alertDialog.setOnShowListener(dialog -> {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) editText.getLayoutParams();
p.setMargins(50, 20, 50, 20); // You can change the margins for your need
editText.requestLayout();
});
Create an Android XML with the needed and formatted Elements. Inflate the XML/view and add view to dialog button.
This way the UI design and the code is cleaner separated. The Android XML Editor with preview makes it easier to get the wanted optical results.
The Example uses Databinding and so the XML/View is addressed via Databinding DialogEditTextBinding.inflate([...]) and the result is accessed via databinding dialogBinding.editText.getText().toString().
Java Code in Fragment/Activity
final DialogEditTextBinding dialogBinding = DialogEditTextBinding.inflate(getLayoutInflater());
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainActivity);
alertDialog.setTitle("Enter Date");
alertDialog.setView(dialogBinding);
alertDialog.setPositiveButton("OK",
(dialog, whichButton) -> {
String editText = dialogBinding.editText.getText().toString();
doSomething(editText);
});
Android XML for Dialog extra Elements
dialog_edit_text.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="22dp"
android:layout_marginEnd="22dp"
android:textSize="12sp"
/>
</LinearLayout>
</layout>
PS
PS: The example is combined out of my code and your code, so it may contain errors.
Building on #LeonardoSibela answer, I made this simple function in kotlin to show a dialog with an edittext and a callback.
private fun showEditDialog(title: String, preFill: String, onSubmit: (text: String) -> Unit) {
val editText = EditText(requireContext()).apply {
setText(preFill)
}
val viewContainer = LinearLayout(requireContext()).apply {
orientation = LinearLayout.VERTICAL
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
).apply {
setMargins(16.dp, 0, 16.dp, 0)
}
addView(editText, lp)
}
MaterialAlertDialogBuilder(requireContext())
.setView(viewContainer)
.setTitle(title)
.setPositiveButton("Ok") { _, _ -> onSubmit(editText.text.toString()) }
.setNegativeButton("Cancel") { _, _ -> }
.show()
}
And you could use it like this:
showEditDialog("Change name", "") { name ->
viewModel.updateName(name)
}
Admob ad not showing in my application. I am sensing ad is loading but somehow its not showing because of my layout arrangement. but i couldn't locate it. here is my code
protected void onSetContentView() {
final RelativeLayout relativeLayout = new RelativeLayout(this);
final FrameLayout.LayoutParams relativeLayoutLayoutParams = new FrameLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
this.mRenderSurfaceView = new RenderSurfaceView(this);
mRenderSurfaceView.setRenderer(mEngine);
final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.FILL_PARENT,
FrameLayout.LayoutParams.FILL_PARENT,Gravity.CENTER);
final android.widget.RelativeLayout.LayoutParams surfaceViewLayoutParams = new RelativeLayout.LayoutParams(layoutParams);
surfaceViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
relativeLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
FrameLayout frameLayout = new FrameLayout(this);
adView = new AdView(this, AdSize.BANNER, "##############");
adView.refreshDrawableState();
adView.setVisibility(AdView.VISIBLE);
frameLayout.addView(adView);
relativeLayout.addView(frameLayout);
this.setContentView(relativeLayout, relativeLayoutLayoutParams);
}
You have told your SurfaceView to FILL_PARENT, so it is taking all the space leaving none for the AdView sibling.
final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.FILL_PARENT,
FrameLayout.LayoutParams.FILL_PARENT,Gravity.CENTER);
Note also there is no need for the FrameLayout wrapping the AdView.
I suggest you follow jquery404's advice and define the layout in XML. You'll get a much better understanding of your ui design.