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
Related
I am inflating an xml having button, multiple times and i am able to do so perfectly but the problem is when I click the button,i want to show which button is clicked.
public class InflateExActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button b;
LinearLayout lLayout;
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 3; i++) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
b = (Button) inflater.inflate(R.layout.buttons, null);
t = (TextView) inflater.inflate(R.layout.texts, null);
b.setTag(i); // you'll get 0,1,2 as
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(this);
}
}
public void onClick(View v) {
}
}
You can use setTag() to each button. Inside the for loop you can assign button.setTag(). And you can use getTag() to retrieve button's tag. After you inflate the layout, add a tag to your button
EDIT2:
You should inflate the layout and then look up for your button id. See below:
public class InflateExActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lLayout;
final Button b = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<3;i++){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.buttons, null);
b = v.findViewById(R.id.your_button_id);
// b = (Button) inflater.inflate(R.layout.buttons, null);
b.setTag(i); // you'll get 0,1,2 as tags
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int specificButton = (Integer)v.getTag();//Changed here.......
Toast.makeText(InflateExActivity.this, "Button Clicked"+Integer.toString(specificButton),
Toast.LENGTH_LONG).show();
}
});
}
}
}
items you are adding programmatically, you must have to assign ids to them.
b.setId(1);
EDITED:
public class DynamicLayoutActivity extends Activity implements OnClickListener{
private static final int MY_BUTTON = 9000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
// add button
Button b = new Button(this);
b.setText("Button added dynamically!");
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setId(MY_BUTTON);
b.setOnClickListener(this);
ll.addView(b);
}
public void onClick(View v) {
Toast toast;
Log.w("ANDROID DYNAMIC VIEWS:", "View Id: " + v.getId());
switch (v.getId()) {
case MY_BUTTON:
toast = Toast.makeText(this, "Clicked on my dynamically added button!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
LATEST:
public class InflateExActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lLayout;
Button b = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<3;i++){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
b = (Button) inflater.inflate(R.layout.buttons, null);
b.setId(i);
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(InflateExActivity.this, "Button Clicked :"+v.getId(),
Toast.LENGTH_LONG).show();
}
});
}
}
Use the view tag
View.setTag(Object tag);
You can set a string or a complex object like a class to the tag.
I am pretty new with Android and I am learning it by reading a Deitel book. I decided to develop an app with tabs and I am using Fragments (as you can see).
I read on my book/on the internet how to implement an onClick event for a button, but when I try to run the app in my Android phone, it crashes.
Code
public class GamesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_games, container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText val1 = (EditText) v.findViewById(R.id.editText1);
EditText val2 = (EditText) v.findViewById(R.id.editText2);
EditText val3 = (EditText) v.findViewById(R.id.editText3);
EditText sol1 = (EditText) v.findViewById(R.id.editText4);
EditText sol2 = (EditText) v.findViewById(R.id.editText5);
//Solve the equation using a method of a class I created
equazioni2grado Equazione = new equazioni2grado();
Equazione.solveEquation(val1.getText().toString(), val2.getText().toString(), val3.getText().toString());
//Show the results
sol1.setText( Equazione.getSol1AsFraction() );
sol2.setText( Equazione.getSol1AsFraction() );
}
});
return view;
}
}
XML
link
I put the XML in a pastebin because it's pretty long. The XML looks like this:
I read that I can define the onClick event in the XML or in the java file, both ways are possible. I am doing it programmatically as you can see.
I can't find where is my mistake. Any idea?
Note: The object Equazione has the method that is:
public void solveEquation(String x, String y, String z) { ... }
EditText val1 = (EditText) v.findViewById(R.id.editText1);
Use view instead of v as below
EditText val1 = (EditText) view.findViewById(R.id.editText1);
try the code below:
public class GamesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_games, container, false);
Button button = (Button) view.findViewById(R.id.button1);
EditText val1 = (EditText) view.findViewById(R.id.editText1);
EditText val2 = (EditText) view.findViewById(R.id.editText2);
EditText val3 = (EditText) view.findViewById(R.id.editText3);
EditText sol1 = (EditText) view.findViewById(R.id.editText4);
EditText sol2 = (EditText) view.findViewById(R.id.editText5);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Solve the equation using a method of a class I created
equazioni2grado Equazione = new equazioni2grado();
Equazione.solveEquation(val1.getText().toString(), val2.getText().toString(), val3.getText().toString());
//Show the results
sol1.setText( Equazione.getSol1AsFraction() );
sol2.setText( Equazione.getSol1AsFraction() );
}
});
return view;
}
}
And can you paste LogCat?
You need to call findViewById on the view that represents the layout you've inflated. In this case, it's the object "view", returned from inflater.inflate().
One way of doing that is declaring view as a final variable and then replacing the calls "v.findViewById..." with "view.findViewById...".
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);
I have a custom ListView with two button and I when I click either button on any row I want to get the text label on the Listview and for now just popup a toast with it. So far nothing has worked I keep getting the last item in my array.
Here is a screen shot to give you a better idea of what i mean
Here is my Adapter subclass for my custom ListView
static final String[] Names =
new String[] { "John", "Mike", "Maria", "Miguel"};
class MyArrayAdapter extends ArrayAdapter<String> {
private final Context context;
int which;
public MyArrayAdapter(Context context, String[] pValues) {
super(context, R.layout.main, pValues);
this.context = context;
values = pValues;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.main, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
Button call = (Button) rowView.findViewById(R.id.button1);
Button chat = (Button) rowView.findViewById(R.id.button2);
textView.setText(values[position]);
// Change icon based on name
s = values[position];
which = position;
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = values[which];
Toast.makeText(CustomListView.this, name, Toast.LENGTH_SHORT).show();
}
});
return rowView;
}
}
Edit:
String name = textView.getText().toString();
RelativeLayout ll = (RelativeLayout)v.getParent();
textView = (TextView)ll.findViewById(R.id.label);
Toast.makeText(CustomListView.this, name,
Toast.LENGTH_SHORT).show();
Easy to do:
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout rl = (RelativeLayout)v.getParent();
TextView tv = (TextView)rl.findViewById(R.id.label);
String text = tv.getText().toString();
Toast.makeText(CustomListView.this, text, Toast.LENGTH_SHORT).show();
}
});
use setTag attribute of the View..............
as
Button call = (Button) rowView.findViewById(R.id.button1);
call.setTag(position);
and
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int which = -1;
Obejct obj = v.getTag();
if(obj instaceof Integer){
which = ((Integer)obj).intValue();
}
if(which >-1){
String name = values[which];
Toast.makeText(CustomListView.this, name, Toast.LENGTH_SHORT).show();
}
}
});
If you have a ListActivity, and you're not using your own adapter, you can still get the list item belonging to the tapped button, like so:
In your layout file of the list row:
<ImageButton
android:id="#+id/button_call"
android:layout_height="48dip"
android:layout_width="48dip"
android:contentDescription="Call"
android:onClick="callBuddy"
android:src="#drawable/call_button_image"
/>
In your ListActivity:
public void callBuddy(View view) {
int position = getListView().getPositionForView((View) view.getParent());
Buddy buddyToCall = (Buddy) getListView().getItemAtPosition(position);
Toast.makeText(MyListActivity.this, String.format("Calling your buddy %s.", buddyToCall.name), Toast.LENGTH_SHORT).show();
}
simply use getItem() and pass the position
Ex:getItem(position).getID()
here getID() method is getter method
Set onClick="click" to xml of button/image/etc...
and in your Activity, do:
public void click(View v) {
final int position = getListView().getPositionForView(v);
String text = getListView().getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext, text, Toast.LENGTH_SHORT).show();
}
I am inflating an xml having button, multiple times and i am able to do so perfectly but the problem is when I click the button,i want to show which button is clicked.
public class InflateExActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button b;
LinearLayout lLayout;
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 3; i++) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
b = (Button) inflater.inflate(R.layout.buttons, null);
t = (TextView) inflater.inflate(R.layout.texts, null);
b.setTag(i); // you'll get 0,1,2 as
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(this);
}
}
public void onClick(View v) {
}
}
You can use setTag() to each button. Inside the for loop you can assign button.setTag(). And you can use getTag() to retrieve button's tag. After you inflate the layout, add a tag to your button
EDIT2:
You should inflate the layout and then look up for your button id. See below:
public class InflateExActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lLayout;
final Button b = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<3;i++){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.buttons, null);
b = v.findViewById(R.id.your_button_id);
// b = (Button) inflater.inflate(R.layout.buttons, null);
b.setTag(i); // you'll get 0,1,2 as tags
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int specificButton = (Integer)v.getTag();//Changed here.......
Toast.makeText(InflateExActivity.this, "Button Clicked"+Integer.toString(specificButton),
Toast.LENGTH_LONG).show();
}
});
}
}
}
items you are adding programmatically, you must have to assign ids to them.
b.setId(1);
EDITED:
public class DynamicLayoutActivity extends Activity implements OnClickListener{
private static final int MY_BUTTON = 9000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
// add button
Button b = new Button(this);
b.setText("Button added dynamically!");
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setId(MY_BUTTON);
b.setOnClickListener(this);
ll.addView(b);
}
public void onClick(View v) {
Toast toast;
Log.w("ANDROID DYNAMIC VIEWS:", "View Id: " + v.getId());
switch (v.getId()) {
case MY_BUTTON:
toast = Toast.makeText(this, "Clicked on my dynamically added button!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
LATEST:
public class InflateExActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lLayout;
Button b = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<3;i++){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
b = (Button) inflater.inflate(R.layout.buttons, null);
b.setId(i);
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(InflateExActivity.this, "Button Clicked :"+v.getId(),
Toast.LENGTH_LONG).show();
}
});
}
}
Use the view tag
View.setTag(Object tag);
You can set a string or a complex object like a class to the tag.