How to set imageViews to single clicks rather than double - java

My android app includes a true/false game.
The user should click either the true or false image one time and the next statement will appear.
I need the user to click the image only once, but it is only allowing for double clicks.
Is there anyway to set the clicks to be single rather than double?
I have checked that the focusable and focusable in touch attributes are null
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#B5FFFFFF"
android:orientation="vertical"
tools:context=".industry_standards_questions">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.38"
android:background="#63FFFFFF">
<TextView
android:layout_width="420dp"
android:layout_height="150dp"
android:gravity="center"
android:text="Know your standards"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#0C40F1"
android:textSize="40dp"
android:textStyle="bold">
</TextView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.38">
<TextView
android:id="#+id/statement_TV"
android:layout_width="420dp"
android:layout_height="150dp"
android:gravity="center"
android:text="Statement"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#020202"
android:textSize="20dp"
android:textStyle="bold">
</TextView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.38"
android:background="#00FFFFFF">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:weightSum="2">
<ImageView
android:id="#+id/trueImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginRight="20dp"
android:src="#drawable/true_button"></ImageView>
<ImageView
android:id="#+id/falseImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="20dp"
android:focusableInTouchMode="true"
android:src="#drawable/false_button"></ImageView>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.38">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:orientation="vertical"
android:padding="20dp"
>
<Button
android:id="#+id/finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:text="Finish"
android:textColor="#050505"
android:background="#E4DABC53"
android:textSize="20dp"
android:textStyle="bold"
>
</Button>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</ScrollView>
package com.example.securityapp;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Collections;
public class industry_standards_questions extends AppCompatActivity {
DatabaseReference databaseUsers;
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseAuth mAuth;
TextView stmnt;
ImageView image_true, image_false;
Button points;
Statements tfStatements;
int statementsLength;
ArrayList<Item> statementList;
int currentStatement = 0;
int grade = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_industry_standards_questions);
databaseUsers = database.getReference();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
stmnt = (TextView) findViewById(R.id.statement_TV);
image_true = (ImageView) findViewById(R.id.trueImage);
image_false = (ImageView) findViewById(R.id.falseImage);
tfStatements = new Statements();
statementsLength = tfStatements.tfStatements.length;
statementList = new ArrayList<>();
points = (Button) findViewById(R.id.final_score);
for(int i = 0; i < statementsLength; i++){
statementList.add(new Item(tfStatements.getStatement(i), tfStatements.getAnswer(i)));
}
Collections.shuffle(statementList);
setStmnt(currentStatement);
image_true.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkAnswer(currentStatement)) {
grade++;
if (currentStatement < statementsLength - 1)
setStmnt(currentStatement);
}
currentStatement++;
if(currentStatement >= statementsLength) { score(); }
}
});
image_false.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkAnswer(currentStatement)){
grade++;
if(currentStatement < statementsLength -1)
setStmnt(currentStatement);
}
currentStatement++;
if(currentStatement >= statementsLength) { score(); }
}
});
}
// show Statement
private void setStmnt(int number){
stmnt.setText(statementList.get(number).getStatement());
}
//check is answer is right
private boolean checkAnswer(int number){
String answer = statementList.get(number).getAnswer();
return answer.equals("true");
}
public void score(){
Users.currentUser.setScore(grade);
databaseUsers.child(Users.currentUserId).setValue(Users.currentUser);
Toast.makeText(this, "You scored " + grade + " points!", Toast.LENGTH_LONG).show();
grade = 0;
}
}

You can set your view to not be focusable with view.setFocusable(false), because if they are focusable, the first touch will "focus" them (which has no effects on ImageViews) and the second will call the onClick()-method.
If it is set to false, you will just need one click to call your onClick()-method.

Related

Clicking on ImageButton prompts Failed without reason

I am trying to create an ImageButton and use it for adding a new note.
But when I click on that ImageButton, a message appears (Failed) without mentioning the reason for the failure.
The xml layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#color/my_primary"
android:padding="16dp"
tools:context=".NoteDetailsActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/title_bar_layout">
<TextView
android:id="#+id/page_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add New Note"
android:textColor="#color/white"
android:textSize="32sp"
android:textStyle="bold" />
<ImageButton
android:layout_width="36dp"
android:layout_height="36dp"
android:id="#+id/save_note_btn"
android:src="#drawable/ic_baseline_done_24"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
app:tint="#color/white"
android:background="?attr/selectableItemBackgroundBorderless"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title_bar_layout"
android:orientation="vertical"
android:padding="16dp"
android:layout_marginVertical="26dp"
android:backgroundTint="#color/white"
android:background="#drawable/rounded_corner">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/notes_title_text"
android:hint="Title"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginVertical="8dp"
android:padding="12dp"
android:textColor="#color/black"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/notes_content_text"
android:hint="Content"
android:minLines="15"
android:gravity="top"
android:textSize="20sp"
android:layout_marginVertical="8dp"
android:padding="12dp"
android:textColor="#color/black"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/delete_note_text_view_btn"
android:text="Delete note"
android:layout_alignParentBottom="true"
android:gravity="center"
android:textSize="18sp"
android:visibility="gone"
android:textColor="#FF0000"/>
And this is my Activity class:
package easy.tuto.notespro;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.DocumentReference;
public class NoteDetailsActivity extends AppCompatActivity {
EditText titleEditText,contentEditText;
ImageButton saveNoteBtn;
TextView pageTitleTextView;
String title,content,docId;
boolean isEditMode = false;
TextView deleteNoteTextViewBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_details);
titleEditText = findViewById(R.id.notes_title_text);
contentEditText = findViewById(R.id.notes_content_text);
saveNoteBtn = findViewById(R.id.save_note_btn);
pageTitleTextView = findViewById(R.id.page_title);
deleteNoteTextViewBtn = findViewById(R.id.delete_note_text_view_btn);
//receive data
title = getIntent().getStringExtra("title");
content= getIntent().getStringExtra("content");
docId = getIntent().getStringExtra("docId");
if(docId!=null && !docId.isEmpty()){
isEditMode = true;
}
titleEditText.setText(title);
contentEditText.setText(content);
if(isEditMode){
pageTitleTextView.setText("Edit your note");
deleteNoteTextViewBtn.setVisibility(View.VISIBLE);
}
saveNoteBtn.setOnClickListener( (v)-> saveNote());
deleteNoteTextViewBtn.setOnClickListener((v)-> deleteNoteFromFirebase() );
}
void saveNote(){
String noteTitle = titleEditText.getText().toString();
String noteContent = contentEditText.getText().toString();
if(noteTitle==null || noteTitle.isEmpty() ){
titleEditText.setError("Title is required");
return;
}
Note note = new Note();
note.setTitle(noteTitle);
note.setContent(noteContent);
note.setTimestamp(Timestamp.now());
saveNoteToFirebase(note);
}
void saveNoteToFirebase(Note note){
DocumentReference documentReference;
if(isEditMode){
//update the note
documentReference = Utility.getCollectionReferenceForNotes().document(docId);
}else{
//create new note
documentReference = Utility.getCollectionReferenceForNotes().document();
}
documentReference.set(note).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//note is added
Utility.showToast(NoteDetailsActivity.this,"Note added successfully");
finish();
}else{
Utility.showToast(NoteDetailsActivity.this,"Failed while adding note");
}
}
});
}
void deleteNoteFromFirebase(){
DocumentReference documentReference;
documentReference = Utility.getCollectionReferenceForNotes().document(docId);
documentReference.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//note is deleted
Utility.showToast(NoteDetailsActivity.this,"Note deleted successfully");
finish();
}else{
Utility.showToast(NoteDetailsActivity.this,"Failed while deleting note");
}
}
});
}
}
Please help me find out the reason and how to solve the problem, thank you.

Problems in Android FirebaseRecyclerView Implementing A Search Users Function

I'm looking to implement a search function. When it runs, logcat is telling me:
E/RecyclerView: No adapter attached; skipping layout.
I have searched SO and the net and the answers tell me that I need to set the adapter and the linear layout manager. As you will see with my code, I set both. Alex Mamo's (#AlexMamo) work on here seems to point me in the right direction but I'm still getting the error.
My Activity
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.MyApp.Objects.ParticipantsObject;
import com.MyApp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class ParticipantsActivity extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_neighbors);
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child("Participants");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(view -> {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(ParticipantsActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("name").startAt(searchText);
FirebaseRecyclerOptions<ParticipantsObject> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<ParticipantsObject>()
.setQuery(firebaseSearchQuery, ParticipantsObject.class)
.build();
class UserHolder extends RecyclerView.ViewHolder {
private TextView imageThumbTextView, nameTextView
UserHolder(View itemView) {
super(itemView);
imageThumbTextView = itemView.findViewById(R.id.profile_image);
nameTextView = itemView.findViewById(R.id.name_text);
}
void setUsers(ParticipantsObject participantsObject) {
String imageThumb = driverObject.getThumb_image();
imageThumbTextView.setText(imageThumb);
String name = participantsObject.getName();
nameTextView.setText(name);
}
}
FirebaseRecyclerAdapter<ParticipantsObject, UserHolder> firebaseRecyclerAdapter;
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ParticipantsObject, UserHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull UserHolder userHolder, int position, #NonNull ParticipantsObject participantsObject) {
userHolder.setUsers(participantsObject);
}
#Override
public UserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UserHolder(view);
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
}
My Activity XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#ffffff"
tools:context="com.MyApp.ParticipantsActivity">
<TextView
android:id="#+id/heading_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Firebase Search"
android:textColor="#555555"
android:textSize="24sp" />
<EditText
android:id="#+id/search_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/heading_label"
android:layout_below="#+id/heading_label"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_toStartOf="#+id/search_btn"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Search here"
android:inputType="textPersonName"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:textColor="#999999"
android:textSize="16sp" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/search_field"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/search_field"
android:layout_marginRight="30dp"
android:background="#android:color/background_light"
app:srcCompat="#mipmap/search_button" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/search_field"
android:layout_marginTop="50dp">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
My list layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
app:srcCompat="#mipmap/ic_default_user" />
<TextView
android:id="#+id/name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="14dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="213dp"
android:layout_marginRight="20dp"
android:layout_toEndOf="#+id/profile_image"
android:text="Username"
android:textColor="#555555"
android:textSize="16sp" />
</RelativeLayout>
Any ideas or advice would be much appreciated.
Your code is setting the adapter only after a button is pushed. Because you didn't set it before the first time the RecyclerView needed to render itself on screen, it's going to warn you about that with the message you see in the log. The RecyclerView must have an adapter attached at the time of rendering in order for it to display anything.

Do not return back to code from onClickListener onClick method

This part of the code is to add 3 EditText lines while the button secbutt is clicked. While all three EditText lines are on the screen, the button should disappear.
Now I do not understand why after entering onClick method and starting plusTextField method, it just adds EditText lines infinitely. I want it to execute once and to return to the beginning of summonButton method. What should I do?
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
int numberOfLinesLeft = 3;
Button secondaryActivityAddButton;
LinearLayout llForSecondaryButton;
LinearLayout llForSecondaryEditText;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void summonButton(View view){
llForSecondaryButton = findViewById(R.id.secondaryButton);
secondaryActivityAddButton = new Button(this);
secondaryActivityAddButton.setText("" + numberOfLinesLeft);
llForSecondaryButton.addView(secondaryActivityAddButton);
secondaryActivityAddButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
plusTextField();
}
});
}
public void plusTextField() {
llForSecondaryEditText = findViewById(R.id.linearLayout1);
// add edittext
et = new EditText(this);
et.setText("text" + numberOfLinesLeft);
llForSecondaryEditText.addView(et);
numberOfLinesLeft--;
}
}
ActivityMain.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.egrishin.task_a_day.MainActivity">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="#string/main_task_title"
android:gravity="center_horizontal"
/>
<EditText
android:id="#+id/main_task_line_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="What is 1 main thing to be done today?"
android:inputType="textMultiLine"
android:layout_margin="16dp"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout0"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="vertical"
>
<TextView
android:id="#+id/textline2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="#string/secondary_task_title"
android:gravity="center_horizontal"
android:onClick="summonButton"
/>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="16dp"
>
</LinearLayout>
<LinearLayout
android:id="#+id/secondaryButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<TextView android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="#string/other_task_title"
android:gravity="center_horizontal"/>
</LinearLayout>
</LinearLayout>
You miss logic of setting the button invisible when counter riches 0 :
public void onClick(View view) {
plusTextField();
if(numberOfLinesLeft == 0) {
view.setVisibility(View.GONE);
}
}
Here is the result, there is no button after adding 3 Edit Texts:

Crash on creating a list size >1 to pass into list view (Index out of bounds)

Im trying to create a dice rolling tool as part of a larger application. However if i try to roll more than 1 dice in my dice roll function the application crashes. Howver as im new to Java i cant seem to find the cause of the index out of bounds error.
DiceActvity.Java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import java.util.ArrayList;
import java.util.List;
public class DiceActivity extends AppCompatActivity
{
ListView LVDiceList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Radio button
final RadioButton rbGreater = (RadioButton) findViewById(R.id.greaterThanRadioB);
final RadioButton rbLess = (RadioButton) findViewById(R.id.lessThanRadioB);
//Edit boxes
final EditText txtDiceType = (EditText) findViewById(R.id.diceTypeEdTxt);
final EditText txtNumberDice = (EditText) findViewById(R.id.numDiceEdTxt);
final EditText txtFilterNum = (EditText) findViewById(R.id.filterNumEdTxt);
//Buttons
Button btnRoll = (Button) findViewById(R.id.rollButton);
Button btnDiscard = (Button) findViewById(R.id.discardButton);
//Display Array
final List<Integer> diceList = new ArrayList<Integer>(10);
//Array Adapter
final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, diceList);
//Set adapter
LVDiceList = (ListView) findViewById(R.id.diceResultListV);
LVDiceList.setAdapter(adapter);
//Roll the dice
btnRoll.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Hide soft keyboard
Utils.hideKeyboard(DiceActivity.this);
//Validation of fields
//If both fields >0
if (Integer.valueOf(txtDiceType.getText().toString()) > 0 && Integer.valueOf(txtNumberDice.getText().toString()) > 0)
{
int number = Integer.valueOf(txtNumberDice.getText().toString());
int sides = Integer.valueOf(txtDiceType.getText().toString());
//Populate array
for (int i=0;i <number; i++)
{
diceList.add(i, rollDice(sides,number).get(i));
}
//Update the list view
adapter.notifyDataSetChanged();
}
return;
}
});
//Clear the list of results
btnDiscard.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
diceList.clear();
adapter.notifyDataSetChanged();
}
});
//Radio Button Validation
rbGreater.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(rbGreater.isChecked() == true)
{
rbLess.setChecked(false);
}
}
});
rbLess.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(rbLess.isChecked() == true)
{
rbGreater.setChecked(false);
};
}
});
}
//Returns a list of rolled dice results
private List<Integer> rollDice(int chance, int amount)
{
final List<Integer> rollArray = new ArrayList<Integer>(amount);
int result;
//Gives a random number between 1 and X,Y number of times
{
//BASE Equation||Min + (int)(Math.random() * ((Max - Min) + 1))
//1 = minimum roll
result = 1 + (int) (Math.random() * ((chance - 1) + 1));
rollArray.add(result);
}
return rollArray;
}
}
content_dice.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="garethgriffiths.tabletopcompanion.DiceActivity"
tools:showIn="#layout/activity_dice">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_NumDice"
android:id="#+id/numDiceTextV"
android:layout_alignBottom="#+id/numDiceEdTxt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:textSize="25dp"
android:textStyle="bold"
android:textAlignment="gravity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/numDiceEdTxt"
android:maxLength="3"
android:text="#string/edText_NumDice"
android:gravity="right"
android:selectAllOnFocus="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/numDiceTextV"
android:layout_toEndOf="#+id/numDiceTextV"
android:numeric="integer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_DiceType"
android:id="#+id/diceTypeTextV"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/numDiceTextV"
android:layout_alignBottom="#+id/diceTypeEdTxt"
android:layout_toLeftOf="#+id/diceTypeEdTxt"
android:layout_toStartOf="#+id/diceTypeEdTxt"
android:textSize="25dp"
android:textStyle="bold"
android:textAlignment="gravity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/diceTypeEdTxt"
android:maxLength="2"
android:text="#string/edText_DiceType"
android:layout_below="#+id/numDiceEdTxt"
android:layout_alignLeft="#+id/numDiceEdTxt"
android:layout_alignStart="#+id/numDiceEdTxt"
android:gravity="right"
android:selectAllOnFocus="true"
android:numeric="integer"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radioB_LessThan"
android:id="#+id/lessThanRadioB"
android:layout_above="#+id/discardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="36dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radioB_GreaterThan"
android:id="#+id/greaterThanRadioB"
android:layout_alignTop="#+id/lessThanRadioB"
android:layout_toRightOf="#+id/lessThanRadioB"
android:layout_toEndOf="#+id/lessThanRadioB"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:maxLength="3"
android:id="#+id/filterNumEdTxt"
android:layout_alignTop="#+id/greaterThanRadioB"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="#string/edText_NumFilter"
android:gravity="center"
android:selectAllOnFocus="true"
android:numeric="integer"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_Discard"
android:id="#+id/discardButton"
android:layout_alignTop="#+id/rollButton"
android:layout_toLeftOf="#+id/rollButton"
android:layout_toStartOf="#+id/rollButton"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_Roll"
android:id="#+id/rollButton"
android:layout_marginTop="108dp"
android:layout_below="#+id/diceTypeTextV"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/diceResultListV"
android:scrollIndicators="right"
android:visibility="visible"
android:layout_below="#+id/discardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
Heres a small Class used to hide softkeyboard thats called in DiceActivity
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard
* Used to close soft keyboard
*/
public class Utils
{
public static void hideKeyboard(Activity activity)
{
// Check if no view has focus:
View view = activity.getCurrentFocus();
if (view != null)
{
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Your method private List<Integer> rollDice(int chance, int amount) returns a list of Integer. And according to your comment inside the method it should have multiple numbers in it.
But this method always returns only one number.
Now you invoke this method here:
for (int i=0;i <number; i++)
{
diceList.add(i, rollDice(sides,number).get(i));
}
You are invoking this method in a loop. Storing the results in a NEW list.
You get an exception because in the second loop get(i) is 1 and there is only 1 entry in this list on index 0.
To correct this is should read: .get(0)
Also this kind of implementation is very messy. Please take a paper and a pencil to figure it out.

Android. How to change tab text color?

I want to set color of the tab text white, i cant find any good tutorial. Can someone help me?
There is my tab activity:
package com.example.dev.nordugrid;
import android.app.TabActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
#SuppressWarnings("deprecation")
public class Busena extends TabActivity {
SharedPreferences prefs;
TextView proxySuteike, proxyGaliojimas;
Button button4;
public int randomInt;
String stringProxyGaliojimas, stringProxySuteike, stringUzduotiesPav, stringUzduotiesJDL, stringKitiFailai;
Button holder;
private ArrayList<Item> m_parts = new ArrayList<Item>();
private Runnable viewParts;
private ItemAdapter m_adapter;
private final String data[] = { "Android", "iPhone", "BlackBerry", "AndroidPeople" };
private final String data2[] = { "Ivykdyta", "Atsaukta", "Einama", "Nusisnekejo" };
List<String> a = new ArrayList<String>();
List<String> b = new ArrayList<String>();
public static void setDefaults(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_busena);
this.setTheme(R.style.listItem);
holder = (Button)findViewById(R.id.button19);
proxyGaliojimas = (TextView)findViewById(R.id.generatenumber);
proxySuteike = (TextView) findViewById(R.id.textView5);
randomInt = Integer.parseInt(getDefaults("proxy", this));
stringProxySuteike = getDefaults("vo", this);
proxyGaliojimas.setText(randomInt + " min.");
proxySuteike.setText(stringProxySuteike);
stringUzduotiesPav = getDefaults("uzduotiesPav", this);
stringUzduotiesJDL = getDefaults("jdlFailoReiksme", this);
stringKitiFailai = getDefaults("kitiFailaiReiksme", this);
ListView list = (ListView)findViewById(R.id.tab1);
m_parts.add(new Item(stringUzduotiesPav, stringUzduotiesJDL));
m_adapter = new ItemAdapter(this, R.layout.row, m_parts);
list.setAdapter(m_adapter);
button4 = (Button) findViewById(R.id.refreshProxy);
TabHost tabHost = getTabHost();
this.setNewTab(this, tabHost, "tab1", R.string.uzduotys, android.R.drawable.star_on, R.id.tab1);
this.setNewTab(this, tabHost, "tab2", R.string.proxy, android.R.drawable.star_on, R.id.tab2);
addListenerOnButton();
}
/*#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}*/
private void setNewTab(Context context, TabHost tabHost, String tag, int title, int icon, int contentID ) {
TabSpec tabSpec = tabHost.newTabSpec(tag);
String titleString = getString(title);
tabSpec.setIndicator(titleString, context.getResources().getDrawable(android.R.drawable.star_on));
tabSpec.setContent(contentID);
tabHost.addTab(tabSpec);
}
public void addListenerOnButton() {
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int skaicius = randomInt;
Random randomGenerator = new Random();
int rand = randomGenerator.nextInt(240-skaicius);
String ats = Integer.toString(randomInt);
proxyGaliojimas.setText(ats + " min.");
randomInt = rand;
}
});
}
}
And this is what I see :
This is tab activity xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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"
tools:context="com.example.dev.nordugrid.Busena"
android:background="#drawable/background"
>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:theme="#style/listItem"
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" />
<LinearLayout
android:id="#+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- antro tabo vaizdas -->
<TextView
android:layout_marginTop="3dp"
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxyGaliojimas"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginLeft="7dp"
android:layout_marginTop="3dp"
android:id="#+id/generatenumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/min"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginTop="3dp"
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxySuteike"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginLeft="7dp"
android:layout_marginTop="3dp"
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxySuteike"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:layout_marginTop="7dp"
android:id="#+id/refreshProxy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/atnaujinti"
android:textColor="#FFFBFB"
android:background="#drawable/border"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
Please someone give me simple example or other help :)
Create this method:-
private static View createTabView(Context context, String tabText) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null, false);
TextView tv = (TextView) view.findViewById(R.id.tabTitleText);
tv.setText(tabText);
return view;
}
Create custom_tab.xml file in layout folder
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabTitleText"
android:layout_width="#dimen/tabWidth"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:clickable="true"
android:paddingTop="#dimen/tabTopPading"
android:paddingBottom="#dimen/tabBottomPading"
android:paddingLeft="#dimen/tabLeftPading"
android:paddingRight="#dimen/tabRightPading"
android:textSize="#dimen/tabTextSize"
android:textColor="#color/themeColor"
android:background="#drawable/tab_selector"/>
finally set
tabHost.newTabSpec("Tab1").setIndicator(createTabView(getApplicationContext(),"Tab_name"))

Categories