I'm new to android programming and I have a simple question. I have a random number, nr and I generate this number of ImageViews in the same location. Now, I want to apply an animation to each of these images, but not in the same time.
Let's say I want the first image to start moving at sec 0, then image2 at sec 2 and so on.
I have the images in an array, imb_items[].
for(int j=0; j<nr;j++){
imb_items[j].startAnimation(translateAnim);
????? how can I put here the delay?
}
I'm trying for a long time to do this, but I just can't do it with handlers or threads...I think I don't get the concept.
I would be very thankful if somebody would help me understand and give me a sample code that will work in my specific case.
thank you!
public class MyActivity extends ActionBarActivity implements OnClickListener {
private TextView mCalculatorDisplay;
private Boolean userIsInTheMiddleOfTypingANumber = false;
private CalculatorBrain mCalculatorBrain;
private static final String DIGITS = "0123456789.";
DecimalFormat df = new DecimalFormat("############");
Animation anim_translate;
public double valoare, produs, scor = 0;
int printfirst, printsecond;
Handler mHandler = new Handler();
int[] idMultiple = new int[]{6, 5, 3, 4, 2};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//Img.setVisibility(View.VISIBLE);
//android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Animation translateAnim = AnimationUtils.loadAnimation(MyActivity.this, R.anim.translate);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
int dpHeight = (int)(displaymetrics.heightPixels / displaymetrics.density );
int dpWidth = (int)(displaymetrics.widthPixels / displaymetrics.density );
ImageView imb1=(ImageView)findViewById(R.id.ImageView1 );
Toast.makeText(getApplicationContext(), "Spiridusii lui Mos Craciun pregatesc jucariile pentru copii.",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Ei au observat ca unele jucarii sunt incomplete. Ajuta-i sa comande piesele lipsa!",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), height+"inaltime"+width,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), dpHeight+"inaltime"+dpWidth,
Toast.LENGTH_LONG).show();
RelativeLayout Layout=(RelativeLayout)findViewById(R.id.rel_banda);
ImageView banda=(ImageView) findViewById(R.id.banda);
mCalculatorBrain = new CalculatorBrain();
mCalculatorDisplay = (TextView) findViewById(R.id.Raspuns_user);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(2);
findViewById(R.id.b0).setOnClickListener(this);
findViewById(R.id.b1).setOnClickListener(this);
findViewById(R.id.b2).setOnClickListener(this);
findViewById(R.id.b3).setOnClickListener(this);
findViewById(R.id.b4).setOnClickListener(this);
findViewById(R.id.b5).setOnClickListener(this);
findViewById(R.id.b6).setOnClickListener(this);
findViewById(R.id.b7).setOnClickListener(this);
findViewById(R.id.b8).setOnClickListener(this);
findViewById(R.id.b9).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
Runnable runnable = new Runnable() {
#Override
public void run() {
{
valoare = Double.parseDouble(String.valueOf(mCalculatorDisplay.getText()));
genereaza_imagini();
check_answer();
}
}
};
mHandler.post(runnable);
//genereaza_imagini dinamic de la una la 9 imagini de un anumit tip
}
//max poate fi 5 sau 9
public void genereaza_imagini() {
final TextView et1, et2;
et1 = (TextView) findViewById(R.id.printfirst);
et2 = (TextView) findViewById(R.id.printsecond);
int nr1 = random(5);
printsecond = random(9);
printfirst = idMultiple[nr1 - 1];
produs = printsecond * printfirst;
et1.setTextSize(13);
et2.setTextSize(13);
et1.setText("nr piese lipsa:" + printfirst);
et2.setText("nr jucarii:" + printsecond);
et1.setVisibility(View.VISIBLE);
et2.setVisibility(View.VISIBLE);
ImageView imb1 = (ImageView) findViewById(R.id.ImageView1);
ImageView imb2 = (ImageView) findViewById(R.id.ImageView2);
ImageView imb3 = (ImageView) findViewById(R.id.ImageView3);
ImageView imb4 = (ImageView) findViewById(R.id.ImageView4);
ImageView imb5 = (ImageView) findViewById(R.id.ImageView5);
ImageView imb6 = (ImageView) findViewById(R.id.ImageView6);
ImageView imb7 = (ImageView) findViewById(R.id.ImageView7);
ImageView imb8 = (ImageView) findViewById(R.id.ImageView8);
ImageView imb9 = (ImageView) findViewById(R.id.ImageView9);
final ImageView[] imb_items = new ImageView[]{imb1, imb2, imb3, imb4, imb5, imb6, imb7, imb8, imb9};
for (int j = 0; j < 9; j++) {
RelativeLayout.LayoutParams lp;
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
int dpHeight = (int) (displaymetrics.heightPixels / displaymetrics.density);
int dpWidth = (int) (displaymetrics.widthPixels / displaymetrics.density);
lp.leftMargin = dpWidth / 2 - dpWidth / 10;
lp.topMargin = dpHeight / 4;
imb_items[j].setLayoutParams(lp);
imb_items[j].getLayoutParams().height = 30;
imb_items[j].getLayoutParams().width = 30;
imb_items[j].setImageResource(0);
imb_items[j].setVisibility(View.GONE);
}
final int i = printsecond; // cate imagini din cele 9
if (nr1 == 1) {
Toast.makeText(getApplicationContext(), "Omizilor le lipsesc 6 picioare.",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj1);
imb_items[j].setVisibility(View.VISIBLE);
}
}
if (nr1 == 2) {
Toast.makeText(getApplicationContext(), "Florilor le lipsesc 5 petale. ",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj2);
imb_items[j].setVisibility(View.VISIBLE);
}
}
if (nr1 == 3) {
Toast.makeText(getApplicationContext(), "Papusilor le lipsesc 3 nasturi. ",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj3);
imb_items[j].setVisibility(View.VISIBLE);
}
}
if (nr1 == 4) {
Toast.makeText(getApplicationContext(), "Masinilor le lipsesc 4 roti. ",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj4);
imb_items[j].setVisibility(View.VISIBLE);
}
}
if (nr1 == 5) {
Toast.makeText(getApplicationContext(), "Robotilor le lipsesc 2 antene. ",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj5);
imb_items[j].setVisibility(View.VISIBLE);
}
}
final Animation translateAnim = AnimationUtils.loadAnimation(MyActivity.this, R.anim.translate);
Thread thread = new Thread() {
public void run() {
while (true) {
try {
for(int j=0; j<i;j++){
imb_items[j].startAnimation(translateAnim); ???????????????????????????????????????????
Thread.sleep(2000);
}
} catch (InterruptedException e) {
Log.v( "tag", "local Thread error");
}
}
}
};
thread.start();
}
public int random(int max) {
Random r = new Random();
int random = r.nextInt(max) + 1;
return random;
}
public void check_answer() {
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
valoare = Double.parseDouble(String.valueOf(mCalculatorDisplay.getText()));
verifica();
}
});
}
//functie care afiseaza la onCreate, cand apas pe buton 2: nr1, nr2, raspuns corect nr1*nr2
public void verifica() {
final TextView et1, et2;
et1 = (TextView) findViewById(R.id.printfirst);
et2 = (TextView) findViewById(R.id.printsecond);
TextView Scor = (TextView) findViewById(R.id.Scorul);
if (produs == valoare) {
Toast.makeText(getApplicationContext(), "Raspunsul este corect! :)",
Toast.LENGTH_SHORT).show();
Log.v("Produsul este corect=", String.valueOf(produs));
scor = scor + 50;
Scor.setText("Scor:" + scor);
} else {
Toast.makeText(getApplicationContext(), "Raspunsul este gresit! :(",
Toast.LENGTH_SHORT).show();
Log.v("Produsul nu este corect=", String.valueOf(produs));
scor = scor - 50;
Scor.setText("Scor:" + scor);
}
// ca sa actualizeze automat text view-ul raspuns user la 0.0
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation("C");
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
genereaza_imagini();
}
// mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
// }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
String buttonPressed = ((Button) v).getText().toString();
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
mCalculatorDisplay.append(buttonPressed);
}
} else {
if (buttonPressed.equals(".")) {
// ERROR PREVENTION
// This will avoid error if only the decimal is hit before an operator, by placing a leading zero
// before the decimal
mCalculatorDisplay.setText(0 + buttonPressed);
} else {
mCalculatorDisplay.setText(buttonPressed);
}
userIsInTheMiddleOfTypingANumber = true;
}
} else {
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation(buttonPressed);
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", mCalculatorBrain.getResult());
outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/banda_bk"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="visible"
tools:context=".MyActivity">
<RelativeLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/rel_banda">
<ImageView
android:id="#+id/banda"
android:visibility="visible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/banda" />
<ImageView
android:id="#+id/ImageView1"
android:layout_marginRight="92dp"
android:layout_marginBottom="52dp"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_toLeftOf="#+id/linearLayout4"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView2"
android:layout_alignLeft="#+id/ImageView1"
android:layout_alignStart="#+id/ImageView1"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView3"
android:layout_marginRight="41dp"
android:layout_toLeftOf="#+id/ImageView2"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView4"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="16dp"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView5"
android:layout_marginTop="25dp"
android:layout_below="#+id/ImageView4"
android:layout_alignLeft="#+id/ImageView4"
android:layout_alignStart="#+id/ImageView4"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView6"
android:layout_alignTop="#+id/ImageView5"
android:layout_alignLeft="#+id/ImageView3"
android:layout_alignStart="#+id/ImageView3"
android:layout_marginTop="14dp"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView7"
android:layout_alignTop="#+id/ImageView6"
android:layout_toRightOf="#+id/ImageView6"
android:layout_marginLeft="22dp"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView8"
android:layout_alignTop="#+id/ImageView7"
android:layout_toRightOf="#+id/ImageView2"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView9"
android:layout_alignTop="#+id/ImageView8"
android:layout_toRightOf="#+id/ImageView8"
android:layout_marginLeft="26dp"
android:visibility="gone"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<LinearLayout
android:id="#+id/row1"
android:layout_width="600dp"
android:layout_height="wrap_content"
android:gravity="bottom">
<Button
android:id="#+id/b0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".15"
android:text="#string/b0"
android:textSize="12sp" />
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b1"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b2"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b3"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b4"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b5"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b6"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b7"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".15"
android:text="#string/b8"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b9"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/buttonClear"
android:layout_width="33dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="#string/buttonClear"
android:textSize="12sp" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linearLayout4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="33dp">
<TextView
android:id="#+id/printfirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0" />
<TextView
android:id="#+id/printsecond"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0" />
<TextView
android:id="#+id/Raspuns_user"
android:layout_width="100dp"
android:layout_weight=".15"
android:maxLines="1"
android:text="0"
android:textColor="#color/textbody"
android:textSize="15sp"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="60dp"
android:layout_height="30dp"
android:textSize="10sp"
android:text="Check" />
<TextView
android:id="#+id/Scorul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/textbody"
android:textSize="10sp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Ajutati spiridusii sa afle numarul total de piese lipsa. "
android:id="#+id/textView"
android:textSize="13dp"
android:textColor="#color/textbody"
android:layout_alignParentTop="true" />
</RelativeLayout>
Try this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// YOUR CODE HERE
}
}, 2000);
Where 2000 is 2 seconds delay/sleep in main thread.
You can use thread concept and in loop you can use sleep function for delay and you can write your code in it
thread = new Thread() {
public void run() {
while (true) {
try {
YOUR FOR LOOP CODE HERE with this line "Thread.sleep(2000);"
} catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
};
thread.start();
For create delay, you can use this code:
try {
Thread.sleep(m); // m is millisecond, if m = 1000 ms then delay = 1 s
}
catch (InterruptedException e) {
e.printStackTrace();
}
If I use this
for(int j=0; j<i;j++) {
final int finalJ = j;
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
imb_items[finalJ].startAnimation(translateAnim);
Log.i("tag", "This'll run 5000 milliseconds later");
}
},
5000 * j
);
}
the problem is that when when the second image starts moving, the first one stops and disappears. I would like all the images to continue their movement.
This is the final solution:
for(int j=0; j<i;j++) {
translateAnim[j].setStartOffset(5000*j);
imb_items[j].startAnimation(translateAnim[j]);
}
Related
I have the following design.
As you can see, the week days text and the "column title" images are not aligned to the GridView items.
Here is the complete xml file:
<?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"
android:weightSum="11"
tools:context="com.test.me.fragments.patientResume">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:background="#drawable/gradient">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/aboveLights"
android:src="#mipmap/above_lights"
android:contentDescription="#string/above_lights" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#mipmap/under_lights"
android:contentDescription="#string/under_lights" />
<com.test.dashboard.view.CircleImageView
android:id="#+id/centerImg"
android:layout_width="104dp"
android:layout_height="104dp"
android:layout_centerInParent="true"
android:background="#mipmap/ic_default_avatar" />
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/PatientName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/aboveLights"
android:layout_alignTop="#id/aboveLights"
android:layout_alignRight="#id/aboveLights"
android:layout_alignBottom="#id/aboveLights"
android:layout_margin="1dp"
android:gravity = "center_horizontal"
android:textSize="20sp"
android:text="Mauricio Affonso"
android:textColor="#color/colorPrimaryDark" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="25dp">
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/took_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/took"
android:textColor="#color/colorPrimaryDark" />
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/took_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/took_header"
android:gravity="center"
android:text="-"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="20dp">
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/missed_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/missed"
android:textColor="#color/colorPrimaryDark" />
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/missed_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/missed_header"
android:layout_alignRight="#+id/missed_header"
android:layout_below="#+id/missed_header"
android:gravity="center"
android:text="-"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp" />
</RelativeLayout>
<com.test.me.wave.WavesView
android:id="#+id/waves_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="#ddf7ff">
<com.test.dashboard.view.widget.RobotoLightTextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/countPatient"
android:textAlignment="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimaryDark"
android:text="1 OF 1"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/titleImages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/backgroundLight">
<ImageView
android:id="#+id/morning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="30dp"
android:maxHeight="30dp"
android:scaleType="fitCenter"
android:src="#mipmap/ic_morning" />
<ImageView
android:id="#+id/noon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="30dp"
android:maxHeight="30dp"
android:src="#mipmap/ic_noon" />
<ImageView
android:id="#+id/evening"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="30dp"
android:maxHeight="30dp"
android:src="#mipmap/ic_evening" />
<ImageView
android:id="#+id/bedtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="30dp"
android:maxHeight="30dp"
android:src="#mipmap/ic_bedtime" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="7"
android:id="#+id/tableContainer"
android:background="#color/backgroundLight">
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/date_layout"
android:layout_margin="#dimen/activity_horizontal_margin"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp" />
<com.test.me.grid.DateLayout
android:id="#+id/date_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="30dp"
android:id="#+id/Sun"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:text="SUN" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="75dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Mon"
android:text="MON" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="120dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Tue"
android:text="TUE" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="167dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Wed"
android:text="WED" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="215dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Thu"
android:text="THU" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="260dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Fri"
android:text="FRI" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="310dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Sat"
android:text="SAT" />
</RelativeLayout>
</LinearLayout>
As you can see the content of RelativeLayout titleImages and the week days text should be aligned to the GridView items but i'm having different results on different phone resolutions. I even tried to dynamically change the positions:
int test[] = new int[2];
int space = grid.getHorizontalSpacing();
int height = grid.getMeasuredHeight() / 7;
int Width = grid.getColumnWidth() / 2;
int paddingTop = grid.getPaddingTop();
int paddingLeft = grid.getPaddingLeft();
Resources r = getResources();
float spacePx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, space + 10, r.getDisplayMetrics()) ;
float paddingTopPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingTop - 7, r.getDisplayMetrics());
float paddingLeftPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingLeft - 12, r.getDisplayMetrics());
grid.getLocationInWindow(test);
for(int i = 0; i < 7; i++){
Days[i].setY(paddingTopPx + (test[1] - grid.getMeasuredHeight()) + ((i +1)* (height)));
}
for(int i = 0; i < 4; i++){
icons[i].setX((paddingLeftPx + test[0]) + (i) * (spacePx + Width));
}
I checked with different layout but all seems not that perfect so the best way to make your view is use single gridview .Almost succeded but you have to work on that more logic to get exactly what you need
<GridView
android:id="#+id/grid_calender"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:numColumns="5"
android:verticalSpacing="0dp" />
day_view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="5dp">
<TextView
android:id="#+id/tv_new"
android:layout_width="#dimen/text_height_width"
android:layout_height="#dimen/text_height_width"
android:layout_centerInParent="true"
android:gravity="center"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/darker_gray" />
</RelativeLayout>
Create adapter with a better logic as needed its an edited code,Please ignore the commented codes Thanks
public class CustomCalendarAdapter extends BaseAdapter {
static final int FIRST_DAY_OF_WEEK = 0;
public ArrayList<Day> dayList = new ArrayList<>();
String[] days;
Context context;
List<Boolean> event_status;
// Calendar local_cal_30 = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
Calendar cal;
public CustomCalendarAdapter(Context context, ArrayList<Day> dayList, List<Boolean> _event_status, Calendar cal) {
this.context = context;
this.dayList = dayList;
this.event_status = _event_status;
this.cal = cal;
cal.set(Calendar.DAY_OF_MONTH, 1);
refreshDays();
}
#Override
public int getCount() {
return days.length;
}
#Override
public Object getItem(int position) {
return dayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
// public int getPrevMonth(){
// if(cal.get(Calendar.MONTH) == cal.getActualMinimum(Calendar.MONTH)){
// cal.set(Calendar.YEAR, cal.get(Calendar.YEAR-1));
// }else{
//
// }
// int month = cal.get(Calendar.MONTH);
// if(month == 0){
// return month = 11;
// }
//
// return month-1;
// }
public int getMonth() {
return cal.get(Calendar.MONTH);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position % 5 == 0) {
v = vi.inflate(R.layout.day_view, null);
TextView day = (TextView) v.findViewById(R.id.tv_new);
if (position / 5 == 0) {
day.setText(R.string.sunday);
} else if (position / 5 == 1) {
day.setText(R.string.monday);
} else if (position / 5 == 2) {
day.setText(R.string.tuesday);
} else if (position / 5 == 3) {
day.setText(R.string.wednesday);
} else if (position / 5 == 4) {
day.setText(R.string.thursday);
} else if (position / 5 == 5) {
day.setText(R.string.friday);
} else if (position / 5 == 6) {
day.setText(R.string.saturday);
}
} else {
Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
Day dayObject = dayList.get(position);
v = vi.inflate(R.layout.day_view, null);
// RelativeLayout rl_outerView = (RelativeLayout) v.findViewById(R.id.rl);
// FrameLayout today = (FrameLayout) v.findViewById(R.id.today_frame);
// FrameLayout event = (FrameLayout) v.findViewById(R.id.event_frame);
// FrameLayout disable_frame = (FrameLayout) v.findViewById(R.id.disable_frame);
// FrameLayout selected_frame = (FrameLayout) v.findViewById(R.id.selected_frame);
TextView tv_date = (TextView) v.findViewById(R.id.tv_new);
Calendar local_cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
tv_date.setVisibility(View.VISIBLE);
// rl_outerView.setVisibility(View.VISIBLE);
// selected_frame.setVisibility(View.GONE);
if (dayObject.getDay() == 0) {
// rl_outerView.setVisibility(View.GONE);
} else {
tv_date.setVisibility(View.VISIBLE);
tv_date.setText(String.valueOf(dayObject.getDay()));//sets the date
}
//Only show 30 days from current date
// if ((dayObject.getDay()<local_cal.get(Calendar.DAY_OF_MONTH) &&
// dayObject.getMonth() == local_cal.get(Calendar.MONTH)) || ((dayObject.getMonth() == local_cal_30.get(Calendar.MONTH))&&
// dayObject.getDay()>local_cal_30.get(Calendar.DAY_OF_MONTH))) {
//Only show upcoming dates from current date
if ((dayObject.getDay() < local_cal.get(Calendar.DAY_OF_MONTH) &&
dayObject.getMonth() == local_cal.get(Calendar.MONTH))) {
//These dates come out of 30 days(Based on current date)
// disable_frame.setVisibility(View.VISIBLE);
} else {
//Rest days come here
// disable_frame.setVisibility(View.GONE);
dayObject.setDisable_date(true);
// event.setVisibility(View.GONE);
tv_date.setTextColor(Color.WHITE);
//Now compare the schedule date list with each date for matches
for (int i = 0; i < CustomGridCalendarView.schedule_list.size(); i++) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date scheduleDate = format.parse(CustomGridCalendarView.schedule_list.get(i).getScheduleDate());
cal = Calendar.getInstance();
cal.setTime(scheduleDate);
if (dayObject.getDay() == cal.get(Calendar.DAY_OF_MONTH) &&
dayObject.getMonth() == cal.get(Calendar.MONTH) &&
dayObject.getYear() == cal.get(Calendar.YEAR)
) {
//Show the event frame, here we got a match date
// event.setVisibility(View.VISIBLE);
// today.setVisibility(View.GONE);
tv_date.setTextColor(context.getResources().getColor(R.color.colorPrimary));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
if (dayObject.isEvent_status()) {
// event.setVisibility(View.GONE);
// selected_frame.setVisibility(View.VISIBLE);
// today.setVisibility(View.GONE);
tv_date.setTextColor(Color.WHITE);
} else {
// selected_frame.setVisibility(View.GONE);
tv_date.setTextColor(Color.WHITE);
}
//Check for current date
if (dayObject.getYear() == local_cal.get(Calendar.YEAR) && dayObject.getMonth() == local_cal.get(Calendar.MONTH)
&& dayObject.getDay() == local_cal.get(Calendar.DAY_OF_MONTH)) {
// today.setVisibility(View.VISIBLE);
// tv_date.setTextColor(Color.WHITE);
// event.setVisibility(View.GONE);
// tv_date.setTypeface(Typeface.DEFAULT_BOLD);
} else {
// today.setVisibility(View.GONE);
}
}
}
return v;
}
public void refreshDays() {
boolean before_current_date = true;
// clear items
dayList.clear();
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH) + 7;
int firstDay = (int) cal.get(Calendar.DAY_OF_WEEK);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
//TimeZone tz = TimeZone.getDefault();
// figure size of the array
if (firstDay == 0) {
days = new String[lastDay + (FIRST_DAY_OF_WEEK * 6)];
} else {
days = new String[lastDay + firstDay - (FIRST_DAY_OF_WEEK + 1)];
}
int j = FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if (firstDay > 0) {
for (j = 0; j < (firstDay - FIRST_DAY_OF_WEEK) + 7; j++) {
days[j] = "";
Day d = new Day(0, 0, 0, false);
dayList.add(d);
}
} else {
for (j = 0; j < (FIRST_DAY_OF_WEEK * 6) + 7; j++) {
days[j] = "";
Day d = new Day(0, 0, 0, false);
dayList.add(d);
}
j = FIRST_DAY_OF_WEEK * 6 + 1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
if (j > 0 && dayList.size() > 0 && j != 1) {
dayList.remove(j - 1);
}
for (int x = 0, i = j - 1; i < days.length; i++) {
Day day;
if (event_status.size() > x) {
day = new Day(dayNumber, year, month, event_status.get(x));
} else {
day = new Day(dayNumber, year, month, false);
}
x++;
Calendar cTemp = Calendar.getInstance();
cTemp.set(year, month, dayNumber);
//int startDay = Time.getJulianDay(cTemp.getTimeInMillis(), TimeUnit.MILLISECONDS.toSeconds(tz.getOffset(cTemp.getTimeInMillis())));
days[i] = "" + dayNumber;
dayNumber++;
dayList.add(day);
}
}
}
Hey I have a button keyboards with green picture if the user press on it disable it(red color) and print it on the text view I have 4 textview so step by step the 4 text view fill the last textview doesn't stand and it's own number its changes every time I press on another enable number how can i disable this
and I want when I click on every textview to delete the number in it and reenable the number that was in it and for example i choose second txt2 and i cleared it by click on it by pressing on a number goes automatically on the second textview
take a look at the picture
Button b1;
Button b2;
Button b3;
Button b4;
Button b5;
Button b6;
Button b7;
Button b8;
Button b9;
Button b0;
Button ent;
Button clr;
String[] values = new String[]{" ", " ", " ", " "};
TextView textView[] = new TextView[4];
int size = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView[0] = (TextView) findViewById(R.id.text_1);
textView[1] = (TextView) findViewById(R.id.text_2);
textView[2] = (TextView) findViewById(R.id.text_3);
textView[3] = (TextView) findViewById(R.id.text_4);
b1 = (Button) findViewById(R.id.button_1);
b2 = (Button) findViewById(R.id.button_2);
b3 = (Button) findViewById(R.id.button_3);
b4 = (Button) findViewById(R.id.button_4);
b5 = (Button) findViewById(R.id.button_5);
b6 = (Button) findViewById(R.id.button_6);
b7 = (Button) findViewById(R.id.button_7);
b8 = (Button) findViewById(R.id.button_8);
b9 = (Button) findViewById(R.id.button_9);
b0 = (Button) findViewById(R.id.button_0);
ent = (Button) findViewById(R.id.button_enter);
clr = (Button) findViewById(R.id.button_clear);
buttonEffect(b0);
buttonEffect(b1);
buttonEffect(b2);
buttonEffect(b3);
buttonEffect(b4);
buttonEffect(b5);
buttonEffect(b6);
buttonEffect(b7);
buttonEffect(b8);
buttonEffect(b9);
buttonEffect(clr);
buttonEffect(ent);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_0:
setText(0);
b0.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b0.setEnabled(false);
break;
case R.id.button_1:
setText(1);
b1.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b1.setEnabled(false);
break;
case R.id.button_2:
setText(2);
b2.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b2.setEnabled(false);
break;
case R.id.button_3:
setText(3);
b3.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b3.setEnabled(false);
break;
case R.id.button_4:
setText(4);
b4.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b4.setEnabled(false);
break;
case R.id.button_5:
setText(5);
b5.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b5.setEnabled(false);
break;
case R.id.button_6:
setText(6);
b6.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b6.setEnabled(false);
break;
case R.id.button_7:
setText(7);
b7.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b7.setEnabled(false);
break;
case R.id.button_8:
setText(8);
b8.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b8.setEnabled(false);
break;
case R.id.button_9:
setText(9);
b9.setBackgroundDrawable(getResources().getDrawable(R.drawable.redww));
b9.setEnabled(false);
break;
case R.id.button_clear:
if (size == 0) {
return;
}
String numberToCleared = values[size - 1];
clearButton(Integer.parseInt(numberToCleared));
size--;
values[size] = " ";
bindText();
break;
case R.id.button_enter:
break;
}
}
private void clearButton(int number) {
switch (number) {
case 0 : b0.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b0.setEnabled(true);
break;
case 1 : b1.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b1.setEnabled(true);
break;
case 2 : b2.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b2.setEnabled(true);
break;
case 3 : b3.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b3.setEnabled(true);
break;
case 4 : b4.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b4.setEnabled(true);
break;
case 5 : b5.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b5.setEnabled(true);
break;
case 6 : b6.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b6.setEnabled(true);
break;
case 7 : b7.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b7.setEnabled(true);
break;
case 8 : b8.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b8.setEnabled(true);
break;
case 9 : b9.setBackgroundDrawable(getResources().getDrawable(R.drawable.greenww));
b9.setEnabled(true);
break;
}
}
public void bindText() {
for (int i = 0; i < 4; i++) {
textView[i].setText(values[i]);
}
}
public void setText(int number) {
if (size == 4) {
clearButton(Integer.parseInt(values[3]));
size--;
}
values[size] = String.valueOf(number);
size++;
bindText();
}
public static void buttonEffect(View button){
button.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.getBackground().setColorFilter(0xe0ffffff, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP: {
v.getBackground().clearColorFilter();
v.invalidate();
break;
}
}
return false;
}
});
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_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">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:gravity="bottom"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true"
android:id="#+id/linearLayout"
android:weightSum="1"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal">
<Button
android:id="#+id/button_1"
android:onClick="onClick"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_weight="1"
android:minHeight="80dp"
android:background="#drawable/button_selector"
android:text="1"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:id="#+id/button_2"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="2"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:id="#+id/button_3"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="3"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_weight="1"
android:background="#112"
android:minHeight="80dp"
android:text="clear"
android:onClick="onClick"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp"
android:textStyle="bold"
android:id="#+id/button_clear" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:orientation="horizontal">
<Button
android:id="#+id/button_4"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="4"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:id="#+id/button_5"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="5"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:id="#+id/button_6"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="6"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:id="#+id/button_enter"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_weight="1"
android:background="#ccc"
android:minHeight="80dp"
android:text="enter"
android:onClick="onClick"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:orientation="horizontal"
android:layout_weight="0.40">
<Button
android:id="#+id/button_7"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="7"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:id="#+id/button_8"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="8"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:id="#+id/button_9"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="9"
android:textColor="#333"
android:textSize="25sp" />
<Button
android:id="#+id/button_0"
android:onClick="onClick"
android:background="#drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:minHeight="80dp"
android:text="0"
android:textColor="#333"
android:textSize="25sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/text_1"
android:layout_width="0dp"
android:layout_height="150dp"
android:gravity="center"
android:textSize="50dp"
android:freezesText="true"
android:background="#drawable/greenww"
android:layout_weight="1"/>
<TextView
android:id="#+id/text_2"
android:layout_width="0dp"
android:layout_height="150dp"
android:gravity="center"
android:background="#drawable/greenww"
android:layout_weight="1"
android:textSize="50dp"
android:freezesText="true"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="#+id/text_3"
android:layout_width="0dp"
android:layout_height="150dp"
android:background="#drawable/greenww"
android:gravity="center"
android:layout_weight="1"
android:textSize="50dp"
android:freezesText="true"
android:layout_marginRight="5dp"/>
<TextView
android:id="#+id/text_4"
android:layout_width="0dp"
android:background="#drawable/greenww"
android:layout_height="150dp"
android:gravity="center"
android:textSize="50dp"
android:freezesText="true"
android:layout_weight="1"/>
</LinearLayout>
Sparse...Arrays are very useful because they can act as a kind of Map while avoiding autoboxing if you're working with primitive data types. For further information regarding available methods, please take a look at the reference.
The following code uses SparseIntArray in two places: for Buttons, we want to map the resource id to the number of each Button.
For TextViews, we need to keep track of their state: are they filled, and if so, with which number? So we use a SparseIntArray only for filled TextViews. The indices from textView are the keys and the numbers are the values.
The Activity will handle clicks on Buttons as well as TextViews. The values array is no longer necessary, the same goes for size.
So here's the entire Activity code - enjoy :)
private static final String EMPTY = " ";
private TextView textView[] = new TextView[4];
private SparseIntArray mapOfButtons, // map id to number
mapOfFilledTextViews; // map array index to value if TextView is filled
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a8__button_on_touch_and_on_click);
initMaps();
textView[0] = (TextView) findViewById(R.id.text_1);
textView[1] = (TextView) findViewById(R.id.text_2);
textView[2] = (TextView) findViewById(R.id.text_3);
textView[3] = (TextView) findViewById(R.id.text_4);
for (TextView tv: textView)
{
tv.setOnClickListener(this);
}
Button b1 = (Button) findViewById(R.id.button_1);
Button b2 = (Button) findViewById(R.id.button_2);
Button b3 = (Button) findViewById(R.id.button_3);
Button b4 = (Button) findViewById(R.id.button_4);
Button b5 = (Button) findViewById(R.id.button_5);
Button b6 = (Button) findViewById(R.id.button_6);
Button b7 = (Button) findViewById(R.id.button_7);
Button b8 = (Button) findViewById(R.id.button_8);
Button b9 = (Button) findViewById(R.id.button_9);
Button b0 = (Button) findViewById(R.id.button_0);
Button ent = (Button) findViewById(R.id.button_enter);
Button clr = (Button) findViewById(R.id.button_clear);
buttonEffect(b0);
buttonEffect(b1);
buttonEffect(b2);
buttonEffect(b3);
buttonEffect(b4);
buttonEffect(b5);
buttonEffect(b6);
buttonEffect(b7);
buttonEffect(b8);
buttonEffect(b9);
buttonEffect(clr);
buttonEffect(ent);
}
#Override
public void onClick(View v)
{
int id = v.getId();
if (v instanceof Button)
{
if (mapOfButtons.indexOfKey(id) < 0)
{ // so this is no number button
if (id == R.id.button_clear)
{
if (mapOfFilledTextViews.size() == 0)
{
return;
}
// get the key = the index for 'textView'
int indexToClear = indexOfRightmostFilledTextView();
// get the value
int numberToClear = mapOfFilledTextViews.get(indexToClear);
clearButton(numberToClear);
clearTextView(indexToClear);
bindText();
}
else if (id == R.id.button_enter)
{
// do something
}
}
else // this is a number button
{
// only accept clicks if there is a free TextView
if (mapOfFilledTextViews.size() == textView.length)
{
Toast.makeText(this,
"First clear one of the selected numbers", Toast.LENGTH_SHORT).show();
return;
}
Button b = (Button)v;
b.setBackgroundResource(R.drawable.redww);
b.setEnabled(false);
int number = mapOfButtons.get(id);
setText(number);
}
}
else if (v instanceof TextView)
{
TextView tv = (TextView)v;
int number = Integer.parseInt(tv.getText().toString() );
// 'indexOfValue()' will work because we don't have duplicate values
int i = mapOfFilledTextViews.indexOfValue(number);
int key = mapOfFilledTextViews.keyAt(i);
clearButton(number);
clearTextView(key);
bindText();
}
}
private static void buttonEffect(View button)
{
button.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
v.getBackground().setColorFilter(0xe0ffffff, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP:
{
v.getBackground().clearColorFilter();
v.invalidate();
break;
}
}
return false;
}
});
}
private void initMaps()
{
// empty in the beginning:
mapOfFilledTextViews = new SparseIntArray(4);
mapOfButtons = new SparseIntArray(10);
mapOfButtons.put(R.id.button_0, 0);
mapOfButtons.put(R.id.button_1, 1);
mapOfButtons.put(R.id.button_2, 2);
mapOfButtons.put(R.id.button_3, 3);
mapOfButtons.put(R.id.button_4, 4);
mapOfButtons.put(R.id.button_5, 5);
mapOfButtons.put(R.id.button_6, 6);
mapOfButtons.put(R.id.button_7, 7);
mapOfButtons.put(R.id.button_8, 8);
mapOfButtons.put(R.id.button_9, 9);
}
private void bindText()
{
int value;
int len = textView.length;
for (int i = 0; i < len; i++)
{
value = mapOfFilledTextViews.get(i, -1);
textView[i].setText(value >= 0 ? String.valueOf(value) : EMPTY);
}
}
private void setText(int number)
{
if (mapOfFilledTextViews.size() >= textView.length)
{
// this should not happen if we check the number
// of free TextViews in onClick()
return;
}
int index = indexOfLowestFreeTextView();
mapOfFilledTextViews.put(index, number);
bindText();
}
private void clearButton(int number)
{
// get the first (in our case only) index with valueAt(index) == number
int index = mapOfButtons.indexOfValue(number);
if (index < 0) // this value does not exist
{
// this should not happen!
// so maybe throw a RuntimeException
return;
}
int id = mapOfButtons.keyAt(index);
Button b = (Button) findViewById(id);
b.setBackgroundResource(R.drawable.greenww);
b.setEnabled(true);
}
private void clearTextView(int index)
{
// remove entry as this TextView is no longer filled
mapOfFilledTextViews.delete(index);
}
/**
*
* #return index (for use with 'textView') if there are filled TextViews, else -1
*/
private int indexOfRightmostFilledTextView()
{
int size = mapOfFilledTextViews.size();
int maxKey = -1;
for (int i = 0; i < size; i++)
{
int iTemp = mapOfFilledTextViews.keyAt(i);
if (iTemp > maxKey )
{
maxKey = iTemp;
}
}
return maxKey;
}
/**
* Get index of leftmost (lowest) free TextView
* #return index for use with 'textView'.
* If all TextViews are filled, return textView.length
*/
private int indexOfLowestFreeTextView()
{
int lowestIndex = textView.length;
// this assumes the TextViews are sorted from left to right in the textView array
for (int key = 0; key < textView.length; key++)
{
if (mapOfFilledTextViews.indexOfKey(key) < 0)
{
lowestIndex = key;
break;
}
}
return lowestIndex;
}
Hi in my application i am using the Viewpager with PagerAdapter. it contains n number of images. but when i rotate the device when viewpager is on first image then the image shift to top left corner and appears very small. please have a look in the attached image.
code which i am using
public class CustomViewPager extends ViewPager {
private final long SWITCH_TIME_INTERVAL = 5000;
public CustomViewPager(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomViewPager(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height)
height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* this Runnable is use for automatically switching the view pager item.
* #author
*/
private Runnable mSwither = new Runnable() {
#Override
public void run() {
if( CustomViewPager.this.getAdapter() != null )
{
int count = CustomViewPager.this.getCurrentItem();
if( count == (CustomViewPager.this.getAdapter().getCount() - 1) )
{
count = 0;
}else
{
count++;
}
//Log.d(this.getClass().getName(), "Curent Page " + count + "");
CustomViewPager.this.setCurrentItem(count, true);
}
CustomViewPager.this.postDelayed(this, SWITCH_TIME_INTERVAL);
}
};
#Override
public boolean onTouchEvent(MotionEvent arg0) {
switch (arg0.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP :
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
break;
default:
removeCallbacks(mSwither);
break;
}
return super.onTouchEvent(arg0);
} }
//PagerAdapter onInstantiateItem code..
#Override
public Object instantiateItem(ViewGroup container, final int position) {
mImageFetcher.setLoadingImage(R.drawable.placeholder_tabportrait);
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.test_fragment1, container, false);
description = (TextView) itemView.findViewById(R.id.description);
title = (TextView) itemView.findViewById(R.id.car_title);
published = (TextView) itemView.findViewById(R.id.date_data);
author = (TextView) itemView.findViewById(R.id.author);
jumbo_tron_image = (ImageView) itemView.findViewById(R.id.jumbo_imgae);
TrayItem trayItem = getData(position);
if (null != trayItem) {
if (trayItem.getType() != null) {
if (trayItem.getImages() != null) {
mImageFetcher.loadImage(trayItem.getImages().getWidget(),
jumbo_tron_image);
}
return itemView;
}
//xml code.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="500dp"
android:background="#color/white">
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical"
>
<ImageView
android:id="#+id/jumbo_imgae"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_height="300dp"
/>
</FrameLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/container_height"
android:layout_below="#+id/main_container">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:id="#+id/linearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:layout_weight="0.5"
android:textColor="#color/black"
android:id="#+id/car_title"
android:maxLines="2"
android:ellipsize="end"
android:textSize="20sp"
android:text=" "/>
<ImageView
android:id="#+id/iv_add_test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:paddingTop="10dp"
android:src="#drawable/add_icon"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/car_title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout2"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/linearLayout3"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:id="#+id/date_data"
android:layout_width="90dp"
android:layout_height="18dp"
android:text=""
android:textSize="13sp"
android:layout_gravity="left"
android:gravity="center"
android:textColor="#color/white"
android:background="#drawable/date_bg"/>
<TextView
android:id="#+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_marginLeft="10dp"
android:textColor="#color/black"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> </RelativeLayout>
Currently I have a layout xml file where I bind many views. Here I am facing a problem. The problem is I can not overlay a view on an (heart image)Imageview. In layout xml file I can set but I can not overlay the view on that imageview.Please help me to figure our.I want the Black Opacity view on the Heart Imageview.
Here is the xmlsource codes. I have marked the important codes with *.
<LinearLayout
android:id="#+id/listlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="top"
android:orientation="vertical" >
<ListView
android:id="#+id/datalist"
style="#style/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
<RelativeLayout
android:id="#+id/layout2"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#F18EA4"
android:gravity="bottom" >
<TextView
android:id="#+id/income_entry_container"
style="#style/LightYellow"
android:layout_width="70dp"
android:layout_height="20dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:gravity="left|center"
android:text="#string/confirm_income" />
<TextView
android:id="#+id/expense"
style="#style/LightYellow"
android:layout_width="70dp"
android:layout_height="20dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/income_entry_container"
android:gravity="left|center"
android:text="#string/confirm_expense" />
<TextView
android:id="#+id/confirm_income_item_TextView"
style="#style/LightYellow"
android:layout_width="70dp"
android:layout_height="20dp"
android:layout_above="#+id/expense"
android:layout_toRightOf="#+id/income_entry_container"
android:gravity="right|center"
android:text="#string/confrim_income_item" />
<TextView
android:id="#+id/confirm_expense_item_TextView"
style="#style/LightYellow"
android:layout_width="70dp"
android:layout_height="20dp"
android:layout_alignLeft="#+id/confirm_income_item_TextView"
android:layout_below="#+id/confirm_income_item_TextView"
android:gravity="right|center"
android:text="#string/confirm_expense_item" />
<TextView
android:id="#+id/confirm_income_amount_TextView"
style="#style/LightYellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="right|center"
android:text="#string/confirm_income_amount" />
<TextView
android:id="#+id/confrim_expnese_amount_TextView"
style="#style/LightYellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/confirm_income_item_TextView"
android:gravity="right|center"
android:text="#string/confirm_expnese_amount" />
<ImageButton
android:id="#+id/up_down_imageButton"
style="#style/UpDownButtonSelector"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginLeft="170dp"
android:layout_marginTop="10dp"
android:contentDescription="#string/up_down_imageButton" />
<TextView
android:id="#+id/save_percentage"
style="#style/LightYellow"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_below="#+id/balance_amount_TextView"
android:layout_toRightOf="#+id/heart_ImageView"
android:gravity="left|center"
android:textSize="14sp" />
<TextView
android:id="#+id/lbl_balance"
style="#style/LightYellow"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/confrim_expnese_amount_TextView"
android:gravity="left|center"
android:text="#string/usable_amount"
android:textSize="12sp" />
**<ImageView
android:id="#+id/heart_ImageView"
style="#style/LightYellow"
android:layout_width="260dp"
android:layout_height="20dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/lbl_balance"
android:contentDescription="#string/heart_content" />**
<TextView
android:id="#+id/balance_amount_TextView"
style="#style/LightYellow"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_alignBaseline="#+id/lbl_balance_amount"
android:layout_alignBottom="#+id/lbl_balance_amount"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/lbl_balance_amount"
android:gravity="right|center"
android:text="#string/balance_amount"
android:textSize="14sp" />
<TextView
android:id="#+id/lbl_balance_amount"
style="#style/LightYellow"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_below="#+id/confrim_expnese_amount_TextView"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/lbl_balance"
android:gravity="right|center"
android:text="#string/lbl_balance_amount"
android:textSize="14sp" />
**<View
android:id="#+id/overlay"
android:layout_width="260dp"
android:layout_height="20dp"
android:layout_below="#+id/lbl_balance" />**
</RelativeLayout>
</RelativeLayout>
Here is the source codes. I have marked the important codes with *.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_buta_confirm, container, false);
listRelativeLayout = (RelativeLayout) v
.findViewById(R.id.fragment_list);
int top = ((ButaColleTabBarActivity) getActivity())
.getActionBarHeight() + 2;
listRelativeLayout.setPadding(0, top, 0, 120);
listLinearLayout = (LinearLayout) v.findViewById(R.id.listlayout);
listLinearLayout.setPadding(0, 0, 0, 160);
ie_adapter = new Income_Expense_Adapter(getActivity(),
android.R.layout.simple_list_item_1, butaColleList);
view = (ListView) v.findViewById(R.id.datalist);
view.setAdapter(ie_adapter);
view.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ButaColle butaColle = butaColleList.get(position);
FragmentManager fragmentManager = getFragmentManager();
ButaColleDetailIncomeExpenseFragment butaDetail = ButaColleDetailIncomeExpenseFragment
.newInstance(butaColle);
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.realTabContent, butaDetail);
fragmentTransaction.addToBackStack("SearchFragment");
fragmentTransaction.commit();
}
});
view.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
view.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
ie_adapter.removeSelection();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_delete_context, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_data:
SparseBooleanArray selected = ie_adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ButaColle butaitem = ie_adapter.getItem(selected
.keyAt(i));
dbhelper.deleteHistoryRecords(butaitem);
ie_adapter.remove(butaitem);
}
}
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
final int checkedCount = view.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
ie_adapter.toggleSelection(position);
}
});
updownImageButton = (ImageButton) v
.findViewById(R.id.up_down_imageButton);
updownImageButton.setBackgroundResource(R.drawable.close01);
updownImageButton.setTag(R.drawable.close01);
updownImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (updownImageButton.getTag().equals((R.drawable.close01))) {
updownImageButton.setBackgroundResource(R.drawable.open01);
updownImageButton.setTag(R.drawable.open01);
int top = ((ButaColleTabBarActivity) getActivity())
.getActionBarHeight() + 2;
listRelativeLayout.setPadding(0, top, 0, 50);
listLinearLayout.setPadding(0, 0, 0, 160);
} else if (updownImageButton.getTag().equals(R.drawable.open01)) {
updownImageButton.setBackgroundResource(R.drawable.close01);
updownImageButton.setTag(R.drawable.close01);
int top = ((ButaColleTabBarActivity) getActivity())
.getActionBarHeight() + 2;
listRelativeLayout.setPadding(0, top, 0, 120);
listLinearLayout.setPadding(0, 0, 0, 160);
}
}
});
int itemCount = 0;
String itemlbl = "item";
incomeItemcount_TextView = (TextView) v
.findViewById(R.id.confirm_income_item_TextView);
itemCount = dbhelper.getItemCount(1);
if (itemCount > 1)
itemlbl = "items";
incomeItemcount_TextView.setText(String.valueOf(itemCount) + itemlbl);
itemCount = 0;
itemlbl = "item";
expenseItemcount_TextView = (TextView) v
.findViewById(R.id.confirm_expense_item_TextView);
itemCount = dbhelper.getItemCount(0);
if (itemCount > 1)
itemlbl = "items";
expenseItemcount_TextView.setText(String.valueOf(itemCount) + itemlbl);
double balance = 0.0;
double incomeAmount = 0.0;
double expenseAmount = 0.0;
incomeAmount_TextView = (TextView) v
.findViewById(R.id.confirm_income_amount_TextView);
incomeAmount = dbhelper.getTotalAmount(1);
incomeAmount_TextView.setText(String.valueOf(incomeAmount) + "$");
expenseAmount_TextView = (TextView) v
.findViewById(R.id.confrim_expnese_amount_TextView);
expenseAmount = dbhelper.getTotalAmount(0);
expenseAmount_TextView.setText(String.valueOf(expenseAmount) + "$");
balance = incomeAmount - expenseAmount;
balance_TextView = (TextView) v
.findViewById(R.id.balance_amount_TextView);
balance_TextView.setText(String.valueOf(balance) + "$");
int percentage = 0;
percentage = (int) ((balance / incomeAmount) * 100);
if (balance > 0) {
heartImageView = (ImageView) v.findViewById(R.id.heart_ImageView);
heartImageView.setImageResource(R.drawable.graph);
percentage_TextView = (TextView) v
.findViewById(R.id.save_percentage);
percentage_TextView.setText(String.valueOf(percentage) + "%");
} else {
heartImageView = (ImageView) v.findViewById(R.id.heart_ImageView);
heartImageView.setImageResource(0);
percentage_TextView = (TextView) v.findViewById(0);
percentage = 0;
}
**View overlay = (View) v.findViewById(R.id.overlay);
int opacity = 200; // from 0 to 255
overlay.setBackgroundColor(opacity * 0x1000000); // black with a variable alpha
RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(300, 36);
overlay.setLayoutParams(params);
overlay.invalidate();**
return v;
}
Please Help me to figure our.Thank you!
Try Changing
**<View
android:id="#+id/overlay"
android:layout_width="260dp"
android:layout_height="20dp"
android:layout_below="#+id/lbl_balance" />**
to
**<View
android:id="#+id/overlay"
android:layout_width="260dp"
android:layout_height="20dp"
android:layout_alignBottom="#+id/heart_ImageView" />**
Changes made: layout alignment and the id of to whom it was aligned
You can try adding rules to the params with the addRule method
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
I'm not near my PC to test, but you may be able to set the view below lbl_balance with the addRule method
Or, try removing the layout params in the code all together. The xml inflates the view, so it is already created. All you need to do in code is set the background color. Which you can also do in the xml with
android:background="#80000000"
I am trying to make something like customised quick badge with some buttons on it. I have successfully desgined it but when i am clicking on those buttons it does nothing. Can someone tell me where am i going wrong.
demo_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/likemenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="30dp"
android:text="Button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" >
</TextView>
<Button
android:id="#+id/likequickaction"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="30dp"
android:text="Button" />
</LinearLayout>
popup_grid_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<FrameLayout
android:id="#+id/header2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10.0dip"
android:background="#drawable/quickaction_top_frame" />
<ImageView
android:id="#+id/arrow_up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#drawable/quickaction_arrow_up" />
<HorizontalScrollView
android:id="#+id/scroll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header2"
android:background="#drawable/quickaction_slider_background"
android:fadingEdgeLength="0.0dip"
android:paddingLeft="1.0dip"
android:scrollbars="none" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#drawable/quickaction_slider_grip_left" />
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/api_buttons" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#drawable/quickaction_slider_grip_right" />
</LinearLayout>
</HorizontalScrollView>
<FrameLayout
android:id="#+id/footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/scroll"
android:background="#drawable/quickaction_bottom_frame" />
</RelativeLayout>
api_buttons.xml
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/quickaction_slider_background" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/one"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="One" />
<Button
android:id="#+id/two"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Two" />
<Button
android:id="#+id/three"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Three" />
<Button
android:id="#+id/four"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Four" />
<Button
android:id="#+id/five"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Five" />
<Button
android:id="#+id/six"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="80dp"
android:minWidth="80dp"
android:text="Six" />
</TableRow>
</HorizontalScrollView>
BetterPopupWindow.java
public class BetterPopupWindow {
protected final View anchor;
private final PopupWindow window;
private View root;
private Drawable background = null;
private final WindowManager windowManager;
public BetterPopupWindow(View anchor) {
this.anchor = anchor;
this.window = new PopupWindow(anchor.getContext());
// when a touch even happens outside of the window
// make the window go away
this.window.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
BetterPopupWindow.this.window.dismiss();
return true;
}
return false;
}
});
this.windowManager = (WindowManager) this.anchor.getContext()
.getSystemService(Context.WINDOW_SERVICE);
onCreate();
}
protected void onCreate() {
}
protected void onShow() {
}
private void preShow() {
if (this.root == null) {
throw new IllegalStateException(
"setContentView was not called with a view to display.");
}
onShow();
if (this.background == null) {
this.window.setBackgroundDrawable(new BitmapDrawable());
} else {
this.window.setBackgroundDrawable(this.background);
}
this.window.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
this.window.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
this.window.setTouchable(true);
this.window.setFocusable(true);
this.window.setOutsideTouchable(true);
this.window.setContentView(this.root);
}
public void setBackgroundDrawable(Drawable background) {
this.background = background;
}
public void setContentView(View root) {
this.root = root;
this.window.setContentView(root);
}
public void setContentView(int layoutResID) {
LayoutInflater inflator = (LayoutInflater) this.anchor.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.setContentView(inflator.inflate(layoutResID, null));
}
public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
this.window.setOnDismissListener(listener);
}
public void showLikePopDownMenu() {
this.showLikePopDownMenu(0, 0);
}
public void showLikePopDownMenu(int xOffset, int yOffset) {
this.preShow();
this.window.setAnimationStyle(R.style.Animations_PopDownMenu);
this.window.showAsDropDown(this.anchor, xOffset, yOffset);
}
public void showLikeQuickAction() {
this.showLikeQuickAction(0, 0);
}
public void showLikeQuickAction(int xOffset, int yOffset) {
this.preShow();
this.window.setAnimationStyle(R.style.Animations_GrowFromBottom);
int[] location = new int[2];
this.anchor.getLocationOnScreen(location);
Rect anchorRect = new Rect(location[0], location[1], location[0]
+ this.anchor.getWidth(), location[1] + this.anchor.getHeight());
this.root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootWidth = this.root.getMeasuredWidth();
int rootHeight = this.root.getMeasuredHeight();
int screenWidth = this.windowManager.getDefaultDisplay().getWidth();
int screenHeight = this.windowManager.getDefaultDisplay().getHeight();
int xPos = ((screenWidth - rootWidth) / 2) + xOffset;
int yPos = anchorRect.top - rootHeight + yOffset;
// display on bottom
if (rootHeight > anchorRect.top) {
yPos = anchorRect.bottom + yOffset;
this.window.setAnimationStyle(R.style.Animations_GrowFromTop);
}
this.window.showAtLocation(this.anchor, Gravity.NO_GRAVITY, xPos, yPos);
}
public void dismiss() {
this.window.dismiss();
}
}
LikeQuickActionDemo.java
public class LikeQuickActionsDemo extends Activity {
private Button likemenuButton;
private Button likequickactionButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.demo_layout);
this.likemenuButton = (Button) this.findViewById(R.id.likemenu);
this.likemenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DemoPopupWindow dw = new DemoPopupWindow(v);
dw.showLikePopDownMenu();
}
});
this.likequickactionButton = (Button) this
.findViewById(R.id.likequickaction);
this.likequickactionButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
DemoPopupWindow dw = new DemoPopupWindow(v);
dw.showLikePopDownMenu(0, 200);
}
});
}
private static class DemoPopupWindow extends BetterPopupWindow implements
OnClickListener {
public DemoPopupWindow(View anchor) {
super(anchor);
}
protected void onCreate() {
// inflate layout
LayoutInflater inflater = (LayoutInflater) this.anchor.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup root = (ViewGroup) inflater.inflate(
R.layout.popup_grid_layout, null);
// setup button events
for (int i = 0, icount = root.getChildCount(); i < icount; i++) {
View v = root.getChildAt(i);
if (v instanceof TableRow) {
TableRow row = (TableRow) v;
for (int j = 0, jcount = row.getChildCount(); j < jcount; j++) {
View item = row.getChildAt(j);
if (item instanceof Button) {
Button b = (Button) item;
b.setOnClickListener(this);
}
}
}
}
// set the inflated view as what we want to display
this.setContentView(root);
}
public void onClick(View v) {
// we'll just display a simple toast on a button click
Button b = (Button) v;
Toast.makeText(this.anchor.getContext(), b.getText(),
Toast.LENGTH_SHORT).show();
this.dismiss();
}
}
}
The problem is in DemoPopupWindow.onCreate method:
ViewGroup root = (ViewGroup) inflater.inflate(
R.layout.popup_grid_layout, null);
for (int i = 0, icount = root.getChildCount(); i < icount; i++) {
View v = root.getChildAt(i);
if (v instanceof TableRow) {
root will be RelativeLayout defined in popup_grid_layout.xml. Later you iterate through all its children and set onclick listeners only if child view is TableRow, which is never the case. I guess what you want there is to find horizontalScrollView1 view and do the same with its children instead, something like:
View horizontalScrollView1 = findViewById(R.id.horizontalScrollView1);
for (int i = 0, icount = horizontalScrollView1.getChildCount(); i < icount; i++) {
View v = horizontalScrollView1.getChildAt(i);
if (v instanceof TableRow) {
...