Error with setWidth in android - android

My problem is that i want change width of my TEXTVIEW (INPUT TEXT).
In emulator that code work success but when i try to work with my app in mobile that crash it.
My answer is: Why my app crash when i try to change .setWidth? and how can i solve my problem?
A lot of thanks.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.binomial);
EditText TextVA, TextVB, TextVC, EtiquetaA, EtiquetaB, EtiquetaC;
TextVA = (EditText)findViewById(R.id.editTextP);
TextVB = (EditText)findViewById(R.id.editTextK);
TextVC = (EditText)findViewById(R.id.editText3);
ArrayList<TextView> listaTexto = new ArrayList<TextView>();
listaTexto.add(TextVA);
listaTexto.add(TextVB);
listaTexto.add(TextVC);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int y = size.y;
int x = size.x;
ResolucionPantalla respant = new ResolucionPantalla(y, x);
for (int i=0;i<listaTexto.size();i++)
//ResolInput METHOD return size in px according to the screen size
listaTexto.get(i).setWidth(respant.ResolInput());
Button BotonCalcular = (Button)findViewById(R.id.buttonCalcular);
BotonCalcular.setOnClickListener(this);
}
EDIT: TextView to EditText

I see several potential issues...
For starters:
TextVA = (TextView)findViewById(R.id.editTextP);
Is R.id.editTextP an EditText? You are casting it as a TextView
And also:
Calling setWidth here will have no effect. There is an onLayout method for each view that gets called after onCreate is finished. The width/height get set to whatever is specified in your XML layout during that call
You can either extend and create your own EditText and override the onLayout method, or you can figure out how to size your views correctly via XML.

Related

Add images in random positions inside a relative layout at run time

Please let me know that how i can add the views like images or button inside a relative layout. But on random position , Max number of images can be 10.
Please help me out. I am attaching a view how i want the final output.
Regards
Amit Sharma
In this case you should consider an AbsoluteLayout, it would make more sense. Since this way you can randomly generate and x and an y position for each child.
There are a ton of examples on the net, here is the first one found by a Google search. The gist is something like this:
To plot something like this on the screen:
You can have an AbsoluteLayout declared like this in your activity xml file:
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- Declare your shapes -->
</AbsoluteLayout>
And then in your Activity or Fragment you will add your Shape objects at random positions, with something like:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
// Establish the working area
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int widthArea = displayMetrics.widthPixels;
int heightArea = displayMetrics.heightPixels;
//Init the random generator
Random r = new Random();
// Then for each Shape
// ...
AbsoluteLayout.LayoutParams pos =
(AbsoluteLayout.LayoutParams)shape.getLayoutParams();
pos.x = r.nextInt(widthArea);
pos.y = r.nextInt(heightArea);
shape.setLayoutParams(pos);
// ...
}
}

In which state activity measure it's view

I have created a custom ViewGroup ReadPage, and in activity I use it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
pager=(ReadPage)findViewById(R.id.readpage);
pager.addArticle("...");
}
While the addArticle need the view's width and height
public void addArticle(String s){
articles.add(new Article(s,getMeasuredWidth(),getMeasuredHeight()));
}
But the measurewidth and measureheight is 0 at that time.
So I want to know at which state the view will be measured so I can get the right value it show in screen.
This answer probably gives you what you need: https://stackoverflow.com/a/1016941/213528
You would maybe use it like this:
private int WIDTH;
private int HEIGHT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
WIDTH = size.x;
HEIGHT = size.y;
pager = (ReadPage)findViewById(R.id.readpage);
pager.addArticle("...");
}
// ...
public void addArticle(String s){
articles.add(new Article(s, WIDTH, HEIGHT));
}
Use ViewTreeObserver
viewToMeasure.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
viewToMeasure.getViewTreeObserver().removeGlobalOnLayoutListener(this);
/* you can get the view's height and width here
using viewToMeasure.getWidth() and viewToMeasure.getHeight()
*/
}
});
Views are measured sometimes later, during a "measure pass". When View structure changes (due to adding , removing, updating a view), a measure and then a layout pass runs that re-calculates the View sizes and locations.
For example, you can set text data to a TextView any time, but the View itself decides how to display it, when it is ready to display it. The text warp etc is calculated then, and not while setting the text.
You should design the View displaying the Article to be similar. You can provide the data, but let View process and display it further when its onSizeChanged() is called. Views can also employ addOnLayoutChangeListener() to know when layout has been done.

increase ListFragment inbuilt empty text view size

I m using listfragment in my app. When the data fails to load I call setEmptyText with the failure message. This works fine on 4 inch phones but on 7 and 10 inch phones the size of the empty textview is very small and hard to read.
4 inch empty text view
7 inch empty text view
How can I increase the size of empty text view?
You can provide your own TextView to be used as the "empty text", it just needs to have android:id="#id/android:empty" and the ListFragment will use it instead of the standard one.
You could then customize the style of this TextView however you like (either statically in the xml layout):
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="... />
or by calling findViewById() in onCreateView():
TextView emptyTextView = (TextView)view.findViewById(android.R.id.empty);
emptyTextView.setTextSize(...);
A (very good) alternative, as #Delblanco commented, is to call getListView().getEmptyView(). It will return either the TextView with id android.R.id.empty (if supplied in the layout), or the standard TextView that is used otherwise.
Here is a drop in extension for ListFragment which changes the size (and color) of the empty view programmatically:
/**
* Abstract list fragment that does customizations of the list style.
*/
public abstract class LoggingListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
TextView emptyView = null;
View possibleEmptyView = view.findViewById(0x00ff0001);
if (possibleEmptyView instanceof TextView) {
emptyView = (TextView) possibleEmptyView;
}
if (emptyView == null) {
possibleEmptyView = getListView().getEmptyView();
if (possibleEmptyView instanceof TextView) {
emptyView = (TextView) possibleEmptyView;
}
}
if (emptyView != null) {
emptyView.setTextColor(getActivity().getResources().getColor(R.color.list_subtitle_normal));
emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
}
return view;
}
}
Create different folders like res/values-sw720dp,res/values-sw600dp,
res/values-v11.
Create dimen.xml with different font size of different screen size.
Use values/dimen.xml:
<resources>
<dimen name="normal_font">16sp </dimen>
</resources>
4.Use in your widget in your xml.
android:textSize="#dimen/normal_font
I would do it a bit differently.
My idea: find out the dimensions of the screen and use a switch/case statement to adjust your textView text's size.
For example:
switch ( area ) {
case 7inch:
TextView emptyTextView = (TextView)view.findViewById(android.R.id.empty);
emptyTextView.setTextSize(...);
break;
case 4inch:
TextView emptyTextView = (TextView)view.findViewById(android.R.id.empty);
emptyTextView.setTextSize(...);
break;
default:
values_not_caught_above;
}
You can find the dimensions of the screen as follows:
If you want the display dimensions in pixels you can use getSize:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
int area = height*width;
If you're not in an Activity you can get the default Display via WINDOW_SERVICE:
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Before getSize was introduced (in API level 13), you could use the getWidth and getHeight methods that are now deprecated:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
I like my way best because it's very easy to just add another case statement for an additional device(may be 10inch screen). Almost nothing in your code will need to change that way.
You may increase the size of the text by calling setEmptyText method with a Spannable, let me show you some code:
String yourEmptyTextMessage = getString(R.string.yourEmptyTextMessage);
Spannable spanText = new SpannableString(yourEmptyTextMessage);
spanText.setSpan(new RelativeSizeSpan(1.5f), 0, yourEmptyTextMessage.length(), 0);
setEmptyText(spanText)
You may want to change 1.5f multiplier value to desired ratio

Why is setWidth/Height not working on EditText?

In the code below setting width and height directly on nameEdit does not work, I have to use setLayoutParams. Why does not setWidth/Height work? This led to a lot of frustration for me before I found the solution.
EditText nameEdit = new EditText( theActivity );
nameEdit.setX(300);
nameEdit.setY(400);
// nameEdit.getLayoutParams().width = 100;
// nameEdit.getLayoutParams().height = 60;
//final EditText edittext = new EditText(this);
nameEdit.setLayoutParams(lparams);
//return edittext;
// nameEdit.setWidth(100);
// nameEdit.setHeight(60);
nameEdit.setBackgroundColor(Color.RED);
((ViewGroup) (theActivity).findViewById( android.R.id.content )).addView( nameEdit );
Why setHeight or setWidth did not work?
setHeight or setWidth has more to do with the line height of the text than the height of the view.
Why setLayoutParams works?
When we set the layout params of the editText, we are telling the parent layout rendering the editText, to set the specified height and width for the view. Therefore, it works fine.
Anyone please feel free to add more details or update my understanding ...
Thanks

Getting the width/height of a layout in Android

I'm wondering how to measure the dimensions of a view. In my case it is aan Absolute Layout. I've read the answers concerning those questions but I still don't get it.
This is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AbsoluteLayout layoutbase = (AbsoluteLayout) findViewById(R.id.layoutbase);
drawOval();
}
public void drawOval(){ //, int screenWidth, int screenHeight){
AbsoluteLayout layoutbase = (AbsoluteLayout) findViewById(R.id.layoutbase);
int screenWidth = layoutbase.getWidth();
int screenHeight = layoutbase.getHeight();
Log.i("MyActivity", "screenWidth: " + screenWidth + ", screenHeight: " +screenHeight);
Coordinates c = new Coordinates(BUTTONSIZE,screenWidth,screenHeight);
...some code ...
((ViewGroup) layoutbase ).addView(mybutton, new AbsoluteLayout.LayoutParams(BUTTONSIZE, BUTTONSIZE, c.mX, c.mY));
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showText(mybutton);
}
});
}
public void showText(View button){
int x = findViewById(LAYOUT).getWidth();
int y = findViewById(LAYOUT).getHeight();
Toast message = Toast.makeText(this, "x: " + x , Toast.LENGTH_SHORT);
message.show();
}
The getWidth() command works great in showText() but it does not in drawOval(). I know it looks a bit different there but I also used the int x = findViewById(LAYOUT).getWidth(); version in drawOval(), and x/y are always 0. I don't really understand why there seems to be no width/height at that earlier point. Even if I actually draw a Button on the Absolute Layout, getWidth() returns 0. Oviously I want to measure the sizes in drawOval().
I think will help you.
LinearLayout headerLayout = (LinearLayout)findviewbyid(R.id.headerLayout);
ViewTreeObserver observer = headerLayout .getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
int headerLayoutHeight= headerLayout.getHeight();
int headerLayoutWidth = headerLayout.getWidth();
headerLayout .getViewTreeObserver().removeGlobalOnLayoutListener(
this);
}
});
}
getWidth() is giving you 0 because onCreate is called before layout actually happens. Due to views being able to have dynamic positions and sizes based on attributes or other elements (fill_parent for example) there's not a fixed size for any given view or layout. At runtime there is a point in time (actually it can happen repeatedly depending on many factors) where everything is actually measured and laid out. If you really need the height and width, you'll have to get them later as you've discovered.
This specially deal with Dimensions so
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
This may help you in managing dimensions.
Note: This returns the display dimensions in pixels - as expected. But the getWidth() and getHeight() methods are deprecated. Instead you can use:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
as also Martin Koubek suggested.
If your goal is to simply draw an oval on the screen, then consider creating your own custom View rather than messing around with AbsoluteLayout. Your custom View must override onDraw(android.graphics.Canvas), which will be called when the view should render its content.
Here is some extremely simple sample code that might help get you started:
public class MainActivity extends Activity {
private final Paint mPaint = new Paint();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
// create a nested custom view class that can draw an oval. if the
// "SampleView" is not specific to the Activity, put the class in
// a new file called "SampleView.java" and make the class public
// and non-static so that other Activities can use it.
private static class SampleView extends View {
public SampleView(Context context) {
super(context);
setFocusable(true);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.CYAN);
// smoothen edges
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4.5f);
// set alpha value (opacity)
mPaint.setAlpha(0x80);
// draw oval on canvas
canvas.drawOval(new RectF(50, 50, 20, 40), mPaint);
}
}
}
This give you screen resolution:
WindowManager wm = (WindowManager)context.getSystemService(context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point outSize = new Point();
display.getSize(outSize);
kabuko's answer is correct, but could be a little more clear, so let me clarify.
getWidth() and getHeight() are (correctly) giving you 0 because they have not been drawn in the layout when you call them. try calling the two methods on the button after addView() (after the view has been drawn and is present in the layout) and see if that gives you the expected result.
See this post for more information.

Categories

Resources