I'm trying to generate a full screen TextView that auto-appends a random binary number to it. I wrote this code:
Button button;
TextView textView;
Random rand;
private static final char[] ALPHA_NUMERIC_STRING = "01".toCharArray();
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,false);
rand = new Random();
textView = (TextView) rootView.findViewById(R.id.textView1);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
for (int i=0; i<1000; i++){
textView.append(String.valueOf(ALPHA_NUMERIC_STRING[rand.nextInt(ALPHA_NUMERIC_STRING.length)]));
}
}
});
button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(5000, 1) {
public void onTick(long millisUntilFinished) {
textView.append(String.valueOf(ALPHA_NUMERIC_STRING[rand.nextInt(ALPHA_NUMERIC_STRING.length)]));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount()) - textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
public void onFinish() {
textView.append("done!");
}
}.start();
}
});
return rootView;
}
This code works fine. It's writing a random string into my textView. The problem comes when my textView becomes really big. When it has a lot of chars, when I add a new char and try to append it, I notice the add and repaint process is really slow.
Does anybody know why is this being slowed down? How can I make it work fast?
PS: this code is located inside a Fragment.
Use TextView inside a ScrollView to display messages with any no.of lines.
I think this is good for your requirement. Try it once.
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="100px"
android:textColor="#f00"
android:textSize="25px"
android:typeface="serif"
android:textStyle="italic"/>
if you want to change dynamically whenever you want use as below:
TextView textarea = (TextView)findViewById(R.id.tv); // tv is id in XML file for TextView
textarea.setTextSize(20);
Related
I'm developing simple android app which should have different texts and text size according to the clicks on it. For implementation I have used ConstraintLayout with TextSwitcher to provide animation when texts are changing. Here are sources:
Layout:
<android.support.constraint.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="com.example.android.counter.layout_main">
<TextSwitcher
android:id="#+id/text_body"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inAnimation="#anim/push_down_in"
android:outAnimation="#anim/push_down_out" />
</android.support.constraint.ConstraintLayout>
Code:
private TextSwitcher mTextBody;
private int mTextSize = 20;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle bundle) {
View view = inflater.inflate(R.layout.layout_main, viewGroup, false);
mTextBody = (TextSwitcher) view.findViewById(R.id.text_body);
mTextBody.setFactory(mViewSwitcherFactory);
mTextBody.setText(getString(R.string.intro_text));
mTextBody.setOnClickListener(mOnSwitcherClickListener);
return view;
}
private ViewSwitcher.ViewFactory mViewSwitcherFactory = new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setTextSize(mTextSize);
return textView;
}
};
private View.OnClickListener mOnSwitcherClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
mTextSize = 40;
mTextBody.setText(getString(R.string.text_after_click));
}
};
The initial load of intro text and size are ok, but after the performing click on it only text changes not text size. So, the question is how one can change text size (larger) dynamically when it comes setFactory method of the TextSwitcher?
Any help would be appreciated.
private View.OnClickListener mOnSwitcherClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
mTextSize = 40;
mTextBody.setText(getString(R.string.text_after_click));
}
};
in above method you are not changing text size you are changing only text
change with
private View.OnClickListener mOnSwitcherClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
mTextSize = 40;
TextView tv = (TextView)mTextBody.getCurrentView();
tv.setText(getString(R.string.text_after_click));
tv.setTextSize(mTextSize);
}
};
I'm currently trying to add a user-defined number of TextViews and EditText to an activity, but can't seem to do it other than hard-coding it by creating a variety of different activities.
The objective of this activity is to take the names of the players, the number of which is relayed by the intent extra from the preceding activity.
I'm trying to add both a TextView saying "Player X: " and an EditText to type the name of the player for each player
I know from this post: How to create a variable number of textviews in android that I have to do this programmatically, however, it does not seem to work for me (the activity remains blank when tested)
I have tried creating a temp LinearLayout to which I add the two views in a for(), still nothing.
Any ideas? Am I on the right track?
Best regards
[EDIT] Code is here :
public class players extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_players);
Bundle extras = new Bundle();
final int numPlayers = extras.getInt("num");
final LinearLayout myLayout = findViewById(R.id.lin_Re);
final ArrayList<Player> players = new ArrayList<>();
int size = numPlayers; // total number of TextViews to add
TextView[] tv = new TextView[size];
TextView temp;
EditText[] et = new EditText[size];
EditText temp2;
LinearLayout temp3;
for (int i = 0; i < size; i++)
{
temp = new TextView(this);
temp2 = new EditText(this);
temp3 = new LinearLayout(this);
temp.setText("Player " + i + " : "); //arbitrary task
// add the textview to the linearlayout
temp3.addView(temp);
temp3.addView(temp2);
tv[i] = temp;
et[i] = temp2;
myLayout.addView(temp3);
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:id="#+id/lin_Re">
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/b_send"/>
</LinearLayout>
There is 2 way to achieve this:
1. Use a RecyclerView [Recommended]
2. Add TextView and EditText ( which is nested in a Horizontal LinearLayout) into a Vertical LinearLayout nested in a ScrollView programmatically
The first solution I describe below is quite simple if you're familiar with RecyclerView or ListView, the second solution (your current track) is a bit tricky but still achievable.
Solution 1:
MainActivity
public class MainActivity extends AppCompatActivity {
RecyclerView mPlayerList;
List<String> mPlayerNames;
PlayerAdapter mAdapter;
EditText mInput;
Button mCreateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayerNames = new ArrayList<>();
// setup recycler view
mPlayerList = findViewById(R.id.player_list);
mPlayerList.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PlayerAdapter();
mPlayerList.setAdapter(mAdapter);
// setup input EditText
mInput = findViewById(R.id.input);
// setup Create button
mCreateButton = findViewById(R.id.create_button);
mCreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// clear old player names
mPlayerNames.clear();
// read user input: number of player:
String input = mInput.getText().toString();
int numberOfPlayer;
try {
numberOfPlayer = Integer.parseInt(input);
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Invalid input!!!", Toast.LENGTH_SHORT).show();
return;
}
for (int i = 0; i < numberOfPlayer; ++i) {
mPlayerNames.add("Player #" + (i + 1));
}
// make change on recycler view
mAdapter.notifyDataSetChanged();
// dismiss keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mInput.getWindowToken(), 0);
}
});
}
private class PlayerAdapter extends RecyclerView.Adapter<PlayerAdapter.PlayerHolder> {
#Override
public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_layout, parent, false);
return new PlayerHolder(v);
}
#Override
public void onBindViewHolder(PlayerHolder holder, int position) {
holder.bind(mPlayerNames.get(position));
}
#Override
public int getItemCount() {
return mPlayerNames.size();
}
public class PlayerHolder extends RecyclerView.ViewHolder {
TextView mPlayerLabel;
EditText mPlayerName;
public PlayerHolder(View itemView) {
super(itemView);
mPlayerLabel = itemView.findViewById(R.id.player_label);
mPlayerName = itemView.findViewById(R.id.player_name);
}
public void bind(String playerName) {
mPlayerLabel.setText(playerName);
mPlayerName.setHint("Name of " + playerName);
}
}
}
}
The sample project can be found here:
https://github.com/raiytu4/stackcase004
I'm use recyclerview and holder adapter. This have textview and maxlines is 4. I want to if user click then expand again click then collapse.
My codes is working but i have an issue;
When i click textview this going to expanded work fine but when i was scroll to down list some textview is automatic expanded state(but i did not touch them).
XML:
<android.support.v7.widget.AppCompatTextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/uiPadding_4dp"
android:maxLines="4"/>
Holder:
private final List<Integer> listReadMore = new ArrayList<>();
public void onBind(final Holder holder, final int position) {
final Obj obj = getObj(position);
final int id = obj.id();
final String text = obj.text();
holder.text.post(new Runnable() {
#Override
public void run() {
if(holder.text.getLineCount() >= maxLine)
listReadMore.add(id);
}
});
holder.text.setText(Kit.doHtmlText(text));
holder.text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listReadMore.contains(id)){
ObjectAnimator animation = ObjectAnimator.ofInt(
holder.text,
"maxLines",
holder.text.getLineCount());
animation.setDuration(600);
animation.start();
listReadMore.remove(listReadMore.indexOf(id));
}else{
ObjectAnimator animation = ObjectAnimator.ofInt(holder.text, "maxLines", 4);
animation.setDuration(400);
animation.start();
listReadMore.add(id);
}
}
});
}
When i was use simplify code I'm having the same problem again..
holder.text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.text.setMaxLines(100);
}
});
I was use https://github.com/Manabu-GT/ExpandableTextView this api but have some issue on recyclerview.
I dont know what can i do..
I have a navigation that extends Fragment Activity.
What I want to do
When I open the navigation I want to start the count Down Timer.
Then when I access a fragment from the navigation I want to populate two text views with the values of minutes and seconds from the count Down Timer, and while I am on this fragment the text views to be updated with values from count Down Timer.
How can I provide that?
Many thanks :).
In navigation:
LayoutInflater inflater = getLayoutInflater();
View v = inflater.inflate(R.layout.settings_activity, null);
TextView remainedMinTextView = (TextView) v
.findViewById(R.id.remainedMinTextView);
TextView remainedSecTextView = (TextView) v
.findViewById(R.id.remainedSecTextView);
Utils.startCountDownTimer(10000, remainedMinTextView, remainedSecTextView);
in utils class i create the count down timer
public static void startCountDownTimer(final long milis,
final TextView remainedMinTextView,
final TextView remainedSecTextView) {
CountDownTimer countDownTimer = new CountDownTimer(milis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
remainedMinTextView.setText(""
+ String.format("%d", TimeUnit.MILLISECONDS
.toMinutes(millisUntilFinished)));
remainedSecTextView
.setText(""
+ String.format(
"%d",
TimeUnit.MILLISECONDS
.toSeconds(millisUntilFinished)
- TimeUnit.MINUTES
.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millisUntilFinished))));
}
#Override
public void onFinish() {
}
}.start();
}
In the fragment where I have the two text views
#SuppressLint("InflateParams")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/** Inflating the layout for this fragment **/
View v = inflater.inflate(R.layout.settings_activity, null);
// minutes/seconds passed in app
remainedMinTextView = (TextView) v
.findViewById(R.id.remainedMinTextView);
remainedMinTextView.setTypeface(Utils.TypeFace(getActivity()));
remainedSecTextView = (TextView) v
.findViewById(R.id.remainedSecTextView);
remainedMinTextView.setTypeface(Utils.TypeFace(getActivity()));
}
Ok here when I click on 5 minutes for example (here is where the text views are updated)
textViewTimer5 = (TextView) v.findViewById(R.id.imageViewTimer5);
textViewTimer5.setTypeface(Utils.TypeFace(getActivity()));
textViewTimer5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Utils.startCountDownTimer(300000, remainedMinTextView, remainedSecTextView);
}
});
If I call the count down from here it works... but what I need is when I open the navigation and start the count down and then I open the the fragment that contains the two text views to be updated with values from count down.
I want to make an app with a long list of strings in a string-array.
What I want to do is have a button la shows a random string when the button is clicked.
Could someone help please.
Thanks
Here is my code :
public class PagesFragment extends Fragment {
public PagesFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
TextView txt = (TextView) rootView.findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/pagefonts.ttf");
txt.setTypeface(font);
TextView tv = (TextView) rootView.findViewById(R.id.jamais);
Button btn = (Button)rootView.findViewById(R.id.next);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String[] myString = getResources().getStringArray(R.array.je_nai_jamais);
tv.setText(myString[rgenerator.nextInt(myString.length)]);
}
});
return rootView;
}
}
I am getting errous here
tv.setText(myString[rgenerator.nextInt(myString.length)]);
This will do it:
public void onClick(View v) {
int i = Math.floor(Math.random() * strings.length);
((Button) v).setText(strings[i]);
}
where strings is your array of strings.
First Generate A Random with in a range of 0 to length of your String . And Then Corresponding to random number Select String element.
Random rnd = new Random();
int myValue = r.nextInt(max-offset)+offset;
yourTextView.setText(yourStringArray[myValue]);
If you want to get the string array from resources you want to do
String[] args = getResources().getStringArray(R.array.yourarray'sname);
Button button = (Button)findViewById(yourbutton'sid);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int number = Math.ceil(Math.random() * args.length);
TextView tv = (TextView)findViewById(yourtextview'sid);
tv.setText(args[number]);
});
Well thanks but none of your codes worked for me so I try around and this one worked for me.
See :
Button next;
public FragmentJeNaiJamais(){}
Random rgenerator = new Random();
Vibrator myVibrator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jamais, container, false);
TextView txt = (TextView) rootView.findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/pagefonts.ttf");
txt.setTypeface(font);
myVibrator = (Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
final TextView iv = (TextView) rootView.findViewById(R.id.jamais);
next = (Button)rootView.findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
myVibrator.vibrate(70);
String[] args = getResources().getStringArray(R.array.je_nai_jamais);
iv.setText(args[new Random().nextInt(args.length)]);
Typeface fonts = Typeface.createFromAsset(getActivity().getAssets(), "fonts/artbrush.ttf");
iv.setTypeface(fonts);
}
});
return rootView;`
}
}
It may be helpful for some one