I've found many answers for populating ImageView ViewFlipper from an array, but not so much help with TextView flippers populated via String[] array. I've tried to model the other suggestions, but what I have isn't quite working. The result right now if the first string in my array displays within the flipper view, but no flipping action occurs, and of course then, no other Strings ever show.
My XML
<ViewFlipper
android:id="#+id/vf_tagFlipperFWR"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
My Code - I get my array from a helper class (FYI getTagArray works elsewhere)
vf_tagFlip = (ViewFlipper) findViewById(R.id.vf_tagFlipperFWR);
String[] tagArrayTemp = numberPickerHelper.getTagArray(this);
for(int i=0; i<tagArrayTemp.length; i++){
setFlipperText(tagArrayTemp[i]);
}
setFlipperText method
private void setFlipperText(String s) {
TextView tv = new TextView(getApplicationContext());
tv.setText(s);
tv.setTextColor(Color.parseColor("#ffffff"));
tv.setTextSize(20);
tv.setGravity(1);
vf_tagFlip.addView(tv);
}
Related
I would like to make TextView counter with my own graphic numbers. How can I do this? Example: integer number will be 14356, so I would like to show this number in TextView as a Drawable:
number1.png + number4.png + number3.png + number5.png + number6.png
Can somebody help me with some hint/tips how to code it? I don't need code, just some tips, or hints. I would like to code myself, just don't know how to start this problem.
Thank you very much.
Create a layout file with a LinearLayout and a few ImageViews in it:
<LinearLayout orientation="horizontal" ...>
<ImageView id="#+id/digit_1000" .../>
<ImageView id="#+id/digit_100" .../>
<ImageView id="#+id/digit_10" .../>
<ImageView id="#+id/digit_1" .../>
</LinearLayout>
Use as many ImageView as needed. Then when you update the number, you can do something like this:
private int[] digitDrawables = {R.drawable.digit_0, R.drawable.digit_1, ...}
private ImageView[] digitViews;
private void initialize() {
// Get image views from layout by ID.
int[] ids = new int[]{R.id.digit_1, R.id.digit_10, R.id.digit_100, R.id.digit_1000};
digitViews = new ImageView[4];
for (int i = 0; i < 4; i++) {
digitViews[i] = findViewById(ids[i]);
}
}
private void updateNumber(int number) {
String str = String.valueOf(number);
// Go over each digit in string, updating the image views with:
// -> digitViews[i].setImageResource(digitDrawables[digit]);
// Hide the image views that you don't need with:
// -> digitViews[i].setVisibility(View.GONE);
}
You can start from there.
SO I would suggest doing this with Constraint Layout Horizontal Chain(in packed Configuration) of Image Views.
In the code you can just update a counter within a loop with 1-sec delay if its count down timmer else do it the way you indent to(game points) and if conditions checking if the new number changes 10's place, 100's place ....100000's place and update accordingly.
In my Android App that where i use Java in Android Studio I want to use a loop to get the inserted Texts from my EditText fields
Could you please help me?
for (int i=0; i==player; i++ ){
myArray[i] = "player"+i.getText().toString();
}
I have EditTextfields which can be declared as player0 until player15.
And Player is my total amount of EditTextfields.
I want to write all the inputs into an array but i get always an error for the part"player"+i" is there an other solution how to handle that?
Simply put, Java does not work that way. You can't generate a variable name from a string.
The easiest way to get what you want is an array.
EditText[] players = {
player0, player1, player2, player3, player4,
player5, player6, player7, player8, player9,
player10, player11, player12, player13, player14, player15
};
List<String> texts = new ArrayList<>(players.length);
for (EditText player : players) {
texts.add(players[i].getText().toString());
}
if you have all the edit text fields in the same layout (Linear layout....)
you can simply access every EditText using a loop by accessing them as childs of the layout
suppose in the xml file you have a linear layout
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
notice that we gave the layout an id (linearLayout)
now from your java code you can simply populate the array by using the following loop
LinearLayout linear= (LinearLayout)findViewById(R.id.linearLayout);
for(int i=0;i<linear.getChildCount();i++)
{
EditText field=linear.getChildAt(i);
array[i]=field.getText().toString();
}
unlike the method you are trying to use this method is more dynamic where you dont have to provide ids for all the editTexts just a single id for your main layout and you would not have to declare a static array with all the ids in your java code
I am writing a simple text/eBook viewer for Android, so I have used a TextView to show the HTML formatted text to the users, so they can browse the text in pages by going back and forth. But my problem is that I can not paginate the text in Android.
I can not (or I don't know how to) get appropriate feedback from the line-breaking and page-breaking algorithms in which TextView uses to break text into lines and pages. Thus, I can not understand where the content ends in the actual display, so that I continue from the remaining in the next page. I want to find way to overcome this problem.
If I know what is the last character painted on the screen, I can easily put enough characters to fill a screen, and knowing where tha actual painting was finished, I can continue at the next page. Is this possible? How?
Similar questions have been asked several times on StackOverflow, but no satisfactory answer was provided. These are just a few of them:
How to paginate long text into pages in Android?
Ebook reader pagination issue in android
Paginate text based on rendered text size
There was a single answer, which seems to work, but it is slow. It adds characters and lines until the page is filled. I don't think this is a good way to do page breaking:
How to break styled text into pages in Android?
Rather than this question, it happens that PageTurner eBook reader does it mostly right, although it is somehow slow.
https://github.com/nightwhistler/pageturner
PS: I am not confined to TextView, and I know line breaking and page breaking algorithms can be quite complex (as in TeX), so I am not looking for an optimal answer, but rather a reasonably fast solution that can be usable by the users.
Update: This seems to be a good start for getting the right answer:
Is there a way of retrieving a TextView's visible line count or range?
Answer: After completing text layout, it is possible to find out the visible text:
ViewTreeObserver vto = txtViewEx.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewTreeObserver obs = txtViewEx.getViewTreeObserver();
obs.removeOnGlobalLayoutListener(this);
height = txtViewEx.getHeight();
scrollY = txtViewEx.getScrollY();
Layout layout = txtViewEx.getLayout();
firstVisibleLineNumber = layout.getLineForVertical(scrollY);
lastVisibleLineNumber = layout.getLineForVertical(height+scrollY);
}
});
NEW ANSWER
PagedTextView library (in Kotlin) summarises the below lying algorithm by extending Android TextView. The sample app demonstrates the usage of the library.
Setup
dependencies {
implementation 'com.github.onikx:pagedtextview:0.1.3'
}
Usage
<com.onik.pagedtextview.PagedTextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
OLD ANSWER
The algorithm below implements text pagination in separation of TextView itself lacking simultaneous dynamic change of both the TextView attributes and algorithm configuration parameters.
Background
What we know about text processing within TextView is that it properly breaks a text by lines according to the width of a view. Looking at the TextView's sources we can see that the text processing is done by the Layout class. So we can make use of the work the Layout class does for us and utilizing its methods do pagination.
Problem
The problem with TextView is that the visible part of text might be cut vertically somewhere at the middle of the last visible line. Regarding said, we should break a new page when the last line that fully fits into a view's height is met.
Algorithm
We iterate through the lines of text and check if the line's bottom exceeds the view's height;
If so, we break a new page and calculate a new value for the cumulative height to compare the following lines' bottom with (see the implementation). The new value is defined as top value (red line in the picture below) of the line that hasn't fit into the previous page + TextView's height.
Implementation
public class Pagination {
private final boolean mIncludePad;
private final int mWidth;
private final int mHeight;
private final float mSpacingMult;
private final float mSpacingAdd;
private final CharSequence mText;
private final TextPaint mPaint;
private final List<CharSequence> mPages;
public Pagination(CharSequence text, int pageW, int pageH, TextPaint paint, float spacingMult, float spacingAdd, boolean inclidePad) {
this.mText = text;
this.mWidth = pageW;
this.mHeight = pageH;
this.mPaint = paint;
this.mSpacingMult = spacingMult;
this.mSpacingAdd = spacingAdd;
this.mIncludePad = inclidePad;
this.mPages = new ArrayList<>();
layout();
}
private void layout() {
final StaticLayout layout = new StaticLayout(mText, mPaint, mWidth, Layout.Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, mIncludePad);
final int lines = layout.getLineCount();
final CharSequence text = layout.getText();
int startOffset = 0;
int height = mHeight;
for (int i = 0; i < lines; i++) {
if (height < layout.getLineBottom(i)) {
// When the layout height has been exceeded
addPage(text.subSequence(startOffset, layout.getLineStart(i)));
startOffset = layout.getLineStart(i);
height = layout.getLineTop(i) + mHeight;
}
if (i == lines - 1) {
// Put the rest of the text into the last page
addPage(text.subSequence(startOffset, layout.getLineEnd(i)));
return;
}
}
}
private void addPage(CharSequence text) {
mPages.add(text);
}
public int size() {
return mPages.size();
}
public CharSequence get(int index) {
return (index >= 0 && index < mPages.size()) ? mPages.get(index) : null;
}
}
Note 1
The algorithm works not just for TextView (Pagination class uses TextView's parameters in the implementation above). You may pass any set of parameters StaticLayout accepts and later use the paginated layouts to draw text on Canvas/Bitmap/PdfDocument.
You can also use Spannable as yourText parameter for different fonts as well as Html-formatted strings (like in the sample below).
Note 2
When all text has the same font size, all lines have equal height. In that case you might want to consider further optimization of the algorithm by calculating an amount of lines that fits into a single page and jumping to the proper line at each loop iteration.
Sample
The sample below paginates a string containing both html and Spanned text.
public class PaginationActivity extends Activity {
private TextView mTextView;
private Pagination mPagination;
private CharSequence mText;
private int mCurrentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagination);
mTextView = (TextView) findViewById(R.id.tv);
Spanned htmlString = Html.fromHtml(getString(R.string.html_string));
Spannable spanString = new SpannableString(getString(R.string.long_string));
spanString.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanString.setSpan(new RelativeSizeSpan(2f), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanString.setSpan(new StyleSpan(Typeface.MONOSPACE.getStyle()), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanString.setSpan(new ForegroundColorSpan(Color.BLUE), 700, spanString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanString.setSpan(new RelativeSizeSpan(2f), 700, spanString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanString.setSpan(new StyleSpan(Typeface.MONOSPACE.getStyle()), 700, spanString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mText = TextUtils.concat(htmlString, spanString);
mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Removing layout listener to avoid multiple calls
mTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
mPagination = new Pagination(mText,
mTextView.getWidth(),
mTextView.getHeight(),
mTextView.getPaint(),
mTextView.getLineSpacingMultiplier(),
mTextView.getLineSpacingExtra(),
mTextView.getIncludeFontPadding());
update();
}
});
findViewById(R.id.btn_back).setOnClickListener(v -> {
mCurrentIndex = (mCurrentIndex > 0) ? mCurrentIndex - 1 : 0;
update();
});
findViewById(R.id.btn_forward).setOnClickListener(v -> {
mCurrentIndex = (mCurrentIndex < mPagination.size() - 1) ? mCurrentIndex + 1 : mPagination.size() - 1;
update();
});
}
private void update() {
final CharSequence text = mPagination.get(mCurrentIndex);
if(text != null) mTextView.setText(text);
}
}
Activity's layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btn_back"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"/>
<Button
android:id="#+id/btn_forward"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"/>
</LinearLayout>
<TextView
android:id="#+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Screenshot:
Take a look at my demo project.
The "magic" is in this code:
mTextView.setText(mText);
int height = mTextView.getHeight();
int scrollY = mTextView.getScrollY();
Layout layout = mTextView.getLayout();
int firstVisibleLineNumber = layout.getLineForVertical(scrollY);
int lastVisibleLineNumber = layout.getLineForVertical(height + scrollY);
//check is latest line fully visible
if (mTextView.getHeight() < layout.getLineBottom(lastVisibleLineNumber)) {
lastVisibleLineNumber--;
}
int start = pageStartSymbol + mTextView.getLayout().getLineStart(firstVisibleLineNumber);
int end = pageStartSymbol + mTextView.getLayout().getLineEnd(lastVisibleLineNumber);
String displayedText = mText.substring(start, end);
//correct visible text
mTextView.setText(displayedText);
Surprisingly finding libraries for Pagination is difficult. I think it's better to use another Android UI element besides TextView. How about WebView?
An example # android-webview-example.
Code snippet:
webView = (WebView) findViewById(R.id.webView1);
String customHtml = "<html><body><h1>Hello, WebView</h1></body></html>";
webView.loadData(customHtml, "text/html", "UTF-8");
Note: This simply loads data onto a WebView, similar to a web browser. But let's not stop with just this idea. Add this UI to using pagination by WebViewClient onPageFinished . Please read on SO link # html-book-like-pagination.
Code snippet from one of the best answer by Dan:
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
...
mWebView.loadUrl("...");
}
});
Notes:
The code loads more data upon page scroll.
On the same webpage, there is a posted answer by Engin Kurutepe to set measurements for the WebView. This is necessary for specifing a page in pagination.
I have not implemented pagination but I think this is a good start and shows promise, should be fast. As you can see, there are developers that have implemented this feature.
Problem
I've been trying to place a couple of TextViews underneath eachother, but I can't seem to get it working. They always overlap eachother in stead of getting placed beneath eachother.
What have I tried
I've tried messing with gravity (which doesn't work with a RelativeLayout), and all sorts of layout parameters. I've concluded that the best solution for me would be to use the RelativeLayout.BELOW parameter. The only problem is I'm trying to find the id of the previous TextView.
I assign the id's for the TextViews using the iterator. It seems I can't use the iterator - 1 to count as an id (even though other answers on SO suggest this works). I've even tried assigning the current TextView to a "previous_tv" variable to use in the next iteration.
I tried finding the TextView I just placed using this.findViewByID and the correct iterator value for the id, this also did not work.
Code
I'm trying to figure out what I should place as an id for my parameter rule. This is the code I'm reffering to -edit, placed full code as per request-:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //Don't show application name on the top of the screen (valuable space)
setContentView(R.layout.activity_task_play); //Set which layout file to use for this activity
//Get the Task that was sent by TaskActivity
this.task = (Task) this.getIntent().getSerializableExtra("TASK_OBJECT");
//Get the Sums for this Task
this.sums = this.task.getSums();
//GridView setup
this.gridview = (GridView) this.findViewById(R.id.gridView_task_play);
ArrayAdapter<String> adapter = this.task.getArrayAdapterForGridView(this);
this.gridview.setAdapter(adapter);
//TextView setup
RelativeLayout layout = (RelativeLayout) this.findViewById(R.id.activity_task_play_relative);
for(int i = 0; i < this.sums.length; i++)
{
//Layout parameters
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
//This variable counts how many times the placeholder text is skipped and a operator (+-/ etc.) is placed in the sum_text.
//This is usefull for placing the correct placeholder for each number in the sum (a, b, c etc.)
int times_skipped = 0;
TextView tv = new TextView(this);
String sum_text = "";
for(int j = 0; j < this.sums[i].getVariables().length; j++)
{
if(this.isParsable(this.sums[i].getVariables()[j]))
{
sum_text += TaskPlayActivity.PLACEHOLDERS[(j - times_skipped)] + " ";
}
else
{
sum_text += this.sums[i].getVariables()[j] + " ";
times_skipped++;
}
}
if(i > 0)
{
params.addRule(RelativeLayout.BELOW, i - 1);
}
tv.setId(i);
tv.setText(sum_text + "= " + this.sums[i].getAnswer());
tv.setTextColor(TaskPlayActivity.COLOURS[i]);
tv.setTextSize(25);
tv.setLayoutParams(params);
layout.addView(tv);
}
}
XMLAdded the XML. I'm not very good in layouts so it could very well be that the fault resides here.
<RelativeLayout
android:id="#+id/activity_task_play_relative"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="220dip"
android:layout_alignParentBottom="true">
<GridView
android:id="#+id/gridView_task_play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#EFEFEF"
android:horizontalSpacing="1dp"
android:numColumns="3"
android:paddingTop="1dp"
android:verticalSpacing="1dp" >
</GridView>
</RelativeLayout>
</RelativeLayout>
Any other suggestions are welcome as well, though I would prefer keeping a RelativeLayout. Thanks in advance.
The documentation of View#setId says the identifier should be a positive number so you should make sure not to use zero as identifier value.
Also you have to create a new LayoutParams instance for each TextView. As it is all your TextViews share the same LayoutParams object and changes to that one object affect all TextViews.
And you could use View#generateViewId to generate an ID and remember the ID of the last iteration.
Seems like you are calling this code in a loop. In that case just put i - 1 (previous view id) as id for the rule.
I want to know if its possible to enlarge a EditText in android from 0 until to fill its parent. I tried several things, but in the moment I have the LinearLayout and the EditText is added by code:
<LinearLayout
android:id="#+id/ll_buscarenlace"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="0.8"
android:gravity="right" >
-
EditText et = (EditText) new EditText(this.act);
LinearLayout ll = (LinearLayout) this.act.findViewById(R.id.ll_buscarenlace);
et.setWidth(0);
ll.addView(et);
for (int i=0; i<=ll.getWidth(); i++){
et.setWidth(i);
Thread.sleep(50);
}
But this is one of many things that I tried to do. Thanks in advance
A possible solution: ScaleAnimation.
EditText editText = (EditText) findViewById(R.id.editText1);
Animation scaleAnimation = new ScaleAnimation(0, 1, 1, 1);
scaleAnimation.setDuration(750);
editText.startAnimation(scaleAnimation);
Not exactly what you're looking for since it scales rather than expands, but it may be of help. The effect is not bad either.
By "make it go from zero to fill-parent", do you mean that you want it to initially be invisible and then, on a button click, become visible?
If so, you don't need to do any resizing - in the layout file set android:layout_width="fill_parent" and make it invisible with android:visibility="gone".
Then, in the onClickListener on your button, you can call et.setVisible(Visibility.VISIBLE).