Why checkbox of android is so slow? - java

Today, I used an Android machine with poor performance. I found the checkbox loading is very slow.
For example:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long t1 = System.currentTimeMillis();
setContentView(R.layout.activity_main);
System.out.println("main cost: " + (System.currentTimeMillis() - t1));
}
}
There is only one Checkbox in the page, this will cost 200ms. If there are 3 or 5 checkbox in activity_main.xml, will cost 1s. What happend?
I compared Switch to Checkbox. Obviously Switch is very very better than Checkbox. If i want to keep to use Checkbox, what should i do?

Why does it happen ?
This is happening because the Checkbox class is very complicated(too much code 😠).
What is the solution ?
You can create a custom layout.
You can use a library.
How to implement ?
1.Custom layout
First create a LinearLayout with horizontal orientation.
Add an ImageView and a TextView in the xml.
Code reference
<LinearLayout
android:id="#+id/checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="7dp">
<ImageView
android:id="#+id/checkImageView"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/checked"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the text for checkbox."
android:layout_gravity="center_vertical"
android:layout_marginStart="15dp"/>
</LinearLayout>
Now the code for it to work.
In your class add this
boolean isChecked = true
Now it will function like this
LinearLayout checkBox = findViewById( R.id.checkbox );
ImageView checkBoxImage = findViewById( R.id.checkImageView );
checkBox.setOnClickListener( v -> {
final Bitmap bmap = ((BitmapDrawable)checkBoxImage.getDrawable()).getBitmap();
Drawable myDrawable = getResources().getDrawable(R.drawable.checked);
final Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
if (bmap.sameAs(myLogo)){
//it is checked
isChecked = false;
checkBoxImage.setImageResource( R.drawable.unchecked );
}else {
isChecked = true;
checkBoxImage.setImageResource( R.drawable.checked );
}
} );
2.Using a library
Use this library.
Sample usage
setChecked(boolean checked); //by default, it's wthout animation
setChecked(boolean checked, boolean animate); //pass true to animate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
final CustomCheckBox scb = (CustomCheckBox) findViewById(R.id.scb);
scb.setOnCheckedChangeListener(new CustomCheckBox.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CustomCheckBox checkBox, boolean isChecked) {
Log.d("CustomCheckBox", String.valueOf(isChecked));
}
});
}
Attributes
Attr
Type
Description
duration
integer
Animation Duration
stroke_width
dimension
The border width when unchecked
color_tick
color
Tick color (visible only when checked)
color_checked
color
Fill color when selected
color_unchecked
color
Fill color when unchecked
color_unchecked_stroke
color
Border color when unchecked
References
Github
Edit 1 (27/1/22)
Because of the comment received by Decent Dabbler , I now remember what it forgot. I actually forgot to mention that the file that takes too long to load is the xml file.This can be proved as we do not always use the class right? Just the view in the xml. If you open the xml file of the checkbox, you find it too big.

Related

How to make discrete seek/progress bar in android?

How to make discrete progress/seek bar like stepper in android. Like we see in whatsapp status stories.
Although it is implemented by so many libraries out there, but i need to implement it without using libraries.
I use views in horizontal linear layout and divide it dynamically based on number of sections or number of status stories need to be shown.
activity_main.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:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/layout_views"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:orientation="horizontal"
android:padding="4dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Click" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
String TAG = "MainActivity";
Button mButton;
int x=0,height,width,numberOfSections;
LinearLayout layoutViews;
ArrayList<View> viewsList =new ArrayList<>();
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//findviews
layoutViews = findViewById(R.id.layout_views);
mButton = (Button) findViewById(R.id.button);
//for getting dimensions of screen
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
height = displayMetrics.heightPixels;
width = displayMetrics.widthPixels;
//suppose we have to cut section into 4 parts
numberOfSections = 10;
width -= (16 + 16*numberOfSections); //reducing length of layout by 16dp from left and right and in between 16dp {in between*number of sections)
width /= numberOfSections;
for(int i=0;i<numberOfSections;i++){
View v = new View(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, 10);
params.setMargins(16,0,0,0); //giving 16dp internal margin between two views
v.setLayoutParams(params);
viewsList.add(v); //adding views in array list for changing color on click of button
v.setBackgroundColor(getResources().getColor(colorAccent));
layoutViews.addView(v);
}
//button onclick function
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonClick();
}
});
}
public void buttonClick(){
viewsList.get(x).setBackgroundColor(getResources().getColor(colorPrimaryDark));
x++;
}
}
Voyella! You have made this dynamic story progress bar, although you can add transition animation in views.

EditText AdjustResize forcing content out of view

I'm currently developing a simple Notes application where the user can input a title and the content of their note. What I am looking to achieve is that when the user clicks the note content (EditText) the soft keyboard comes up and only the note content EditText reduces in size (resizes) whilst everything else remains in the same position.
My current implementation can be seen below:
Manifest:
<activity android:theme="#style/AppTheme"
android:name=".AddActivity"
android:label="#string/add_record"
android:windowSoftInputMode="adjustResize"
android:parentActivityName=".MainActivity"
android:excludeFromRecents="true"/>
XML - Add Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/add_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<EditText
android:id="#+id/title_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_title"
android:inputType="textCapSentences"
android:textColor="#color/fontPrimary"
android:theme="#style/EditTextCustomCursor">
<requestFocus />
</EditText>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/modify_scrollview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="false"
android:isScrollContainer="false"
android:fillViewport="true">
<EditText
android:id="#+id/note_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#null"
android:ellipsize="end"
android:gravity="top|left"
android:hint="#string/enter_note"
android:inputType="textCapSentences|textMultiLine"
android:paddingLeft="5dp"
android:scrollHorizontally="false"
android:textColor="#color/fontPrimary"
android:theme="#style/EditTextCustomCursor" />
</ScrollView>
</LinearLayout>
Java - Add Activity
private int screenHeight;
private int actionBarHeight = 350;
private int keyboardHeight;
...
private void setupListeners() {
final LinearLayout layout = (LinearLayout) findViewById(R.id.add_record);
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Rect r = new Rect();
layout.getWindowVisibleDisplayFrame(r);
screenHeight = layout.getRootView().getHeight();
keyboardHeight = screenHeight - (r.bottom - r.top);
Log.d("Keyboard Size", "Size: " + keyboardHeight);
}
});
KeyboardVisibilityEvent.setEventListener(
AddActivity.this,
new KeyboardVisibilityEventListener() {
#Override
public void onVisibilityChanged(boolean isOpen) {
if (isOpen) {
Log.d("KB", "openKeyboard");
scrollView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, screenHeight - actionBarHeight - keyboardHeight));
} else {
Log.d("KB", "closeKeyboard");
scrollView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
}
}
});
}
This is using the Keyboard library (https://github.com/yshrsmz/KeyboardVisibilityEvent) to detect when the keyboard is opened or closed. This works perfectly and the height / layout is adjusted just how I want it to look but only if the user clicks at the top of the EditText. If the user clicks at the bottom of the EditText (if they have entered a long note) then the whole layout gets pushed up leaving a large gap at the bottom of the page.
Therefore, is there any way how wherever in the EditText / ScrollView the user clicks, for it to only adjust that one EditText in height and leave the other EditText in place at the top of the screen without pushing it and the SupportActionBar out of view? Also, the ScrollView is being used to achieve the vertical scrollbar on the right side of the screen - if this same behaviour can be achieved using just the EditText, then I would remove the ScrollView altogether.
EDIT - Add Photos
Image 1: Long note content (bottom of note content is at the bottom of the scrollView (which cannot be seen, until scrolled))
Image 2: Same note but clicking at the bottom, forces the top EditText and Support ActionBar out of view whilst leaving a gap at the bottom.
Explanation: Where the F is highlighted (in Image 2) that is the bottom of the EditText / ScrollView so you can see the large gap created between the top of the soft keyboard and the bottom of the EditText / ScrollView
Desired behaviour: Clicking anywhere in the bottom EditText should only resize that particular EditText to make room for the soft keyboard and ensure that this EditText is above the soft keyboard so the user can see what they are typing whilst the top EditText remains in the same position throughout.
Its because you're adding edittext in a scroll view. why do you even need scroll view? scroll view have a property of going to specific line when keyboard pop-up which is causing this behavior. if you really want to use scrollview, then add master layout as scrollview. add one direct child aka linear layout in there and add all the content in that linear layout.
I have managed to resolve most of this by doing the following:
Removing the ScrollView
Subclassing EditText (to receive the close keyboard button)
Adding a height-change listener
Adding the scroll bars property to the EditText
Manifest:
<activity android:theme="#style/AppTheme"
android:name=".AddActivity"
android:label="#string/add_record"
android:windowSoftInputMode="adjustNothing"
android:parentActivityName=".MainActivity"
android:excludeFromRecents="true"/>
XML - Add Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/add_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
android:windowSoftInputMode="stateHidden">
<EditText
android:id="#+id/title_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_title"
android:inputType="textCapSentences"
android:textColor="#color/fontPrimary"
android:theme="#style/EditTextCustomCursor">
<requestFocus />
</EditText>
<com.securenotes.ExtendedEditText
android:id="#+id/note_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#null"
android:ellipsize="end"
android:gravity="top|left"
android:hint="#string/enter_note"
android:inputType="textCapSentences|textMultiLine"
android:lines="50"
android:maxLines="20"
android:minLines="5"
android:paddingLeft="5dp"
android:scrollHorizontally="false"
android:scrollbars="vertical"
android:textColor="#color/fontPrimary"
android:theme="#style/EditTextCustomCursor" />
</LinearLayout>
Java - Add Activity:
private Boolean initialStart = true;
private Boolean isOpened = false;
...
private void setupListeners() {
final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
Log.d("KB", "HeightDiff: " + heightDiff);
if (heightDiff > 100) { // 99% of the time the height diff will be due to a keyboard.
if (!isOpened && initialStart) {
Log.d("KB", "1) openKeyboard");
//Do two things, make the view top visible and the editText smaller
noteEditText.setLines(15);
noteEditText.requestLayout();
initialStart = false;
isOpened = true;
} else if (!isOpened && noteEditText.hasFocus()) {
Log.d("KB", "2) openKeyboard");
//Do two things, make the view top visible and the editText smaller
noteEditText.setLines(15);
noteEditText.requestLayout();
isOpened = true;
}
}
}
});
noteEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("KB", "EditText onClick");
isOpened = false;
}
});
noteEditText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Log.d("KB", "closeKeyboard");
noteEditText.setLines(50);
noteEditText.requestLayout();
}
return false;
}
});
}
Java - Subclassed EditText:
public class ExtendedEditText extends EditText {
public ExtendedEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ExtendedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExtendedEditText(Context context) {
super(context);
}
#Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
dispatchKeyEvent(event);
return false;
}
return super.onKeyPreIme(keyCode, event);
}
}
However, the one remaining issue is that if the user is scrolling the EditText, sometimes it detects it as a click rather than a scroll so the keyboard is then made visible and the layout (number of lines) is changed. I looked into the onScrollChangeListener but this requires API 23 and my current minimum is 15 - is there any way around this to tell the difference between a scroll and an actual click on the EditText?

Dynamically created TextView in FrameLayout has no width

I'm trying to add a TextView in code to a framelayout. This sits above an imageview in the z order of the framelayout. The ultimate aim is to allow the creation of a screenshot from the framelayout that shows the image and the text that has been overlayed on to it. I have this working when using a textview created in xml but not in the dynamic code version. The create bitmap method returns an error complaining about the width of the textbox being 0. In the code below I am trying to capture just the textview as an image to identify what the issue is, as the captured image from the framelayout did not contain the contents of the textview as expected. In doing this I was able to find the width error and I believe it is this that is the root of the problem. I have tried to set the textview's width using setWidth and also using the LayoutParams. The end result is always that the textview has no width although it can be seen on the handset clearly. I think I am missing something between the dynamic creation and the existing xml which results in the 0 width. Can anyone point me in the correct direction please?
The code is as follows
public void applyTextToImage(View view) {
// Do something in response to button
//Hide the virtual keyboard
InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//Get the text to overlay on the image
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
//Bring the overlay layout to the front
//LinearLayout overlay_layout = (LinearLayout) findViewById(R.id.image_Overlay_Layout);
//overlay_layout.bringToFront();
//Apply the new text to the text box
/* Old code to get the view that is shown in the layout
TextView text_overlay = (TextView) findViewById(R.id.image_Overlay);
text_overlay.bringToFront();
text_overlay.setText(message);
*/
//New code to create a view dynamically instead
TextView text_Overlay = new TextView(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
text_Overlay.setId(Utils.generateViewId());
}
else
{
text_Overlay.setId(TextView.generateViewId()); //static class
}
FrameLayout image_Layout = (FrameLayout) findViewById(R.id.image_Layout);
//View image_Layout = (View) findViewById(R.id.image_Layout);
//FrameLayout.LayoutParams fParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams fParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
fParams.gravity = Gravity.CENTER;
// text_Overlay.setMaxWidth(image_Layout.getWidth());
// text_Overlay.setWidth(image_Layout.getWidth());
//image_Layout.addView(text_Overlay, fParams);
image_Layout.addView(text_Overlay, fParams);
Toast.makeText(this,"TextView Width: " + text_Overlay.getWidth(),Toast.LENGTH_LONG).show();
//TODO: Something has forced the dynamic layout to not be saved in the bitmap try removing the params and set the values on the textview itself
//TODO: for some reason the width keeps coming back as 0 could be that the image_Layout is 0 too
text_Overlay.setGravity(Gravity.CENTER);
text_Overlay.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
//text_Overlay.setWidth(250dp);
text_Overlay.setTextSize(pixels);
text_Overlay.setTextColor(Color.RED);
text_Overlay.bringToFront();
text_Overlay.setText(message);
text_Overlay.setVisibility(View.VISIBLE);
//End of new dynamic code
if (folderCheck()){
try {
String filePath = getFilePath();
int myId = text_Overlay.getId();
Bitmap bitmap;
View v1 = findViewById(myId);
v1.setDrawingCacheEnabled(true);
v1.buildDrawingCache();
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
// End imported code
streamBitmapToFile(bitmap, filePath);
}
catch (Exception e)
{
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG);
Log.e("Bitmap Creation","Couldn't create bitmap error as: " + e.toString());
}
}
}
XML contents
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout 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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="false">
<!--app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_my"-->
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
android:enabled="false"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="applyTextToImage"
android:enabled="false"
android:id="#+id/overlayButton"/>
</LinearLayout>
<FrameLayout
android:id="#+id/image_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true">
<ImageView
android:id="#+id/image_View"
android:layout_width="match_parent"
android:layout_height="250dp" />
<!--<TextView
android:id="#+id/image_Overlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:textSize="25dp"
android:textColor="#ff0000"/>-->
</FrameLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/open_gallery"
android:onClick="openGallery">
</Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_image"
android:onClick="newImage">
</Button>
</LinearLayout>
</RelativeLayout>
The view has not been measured yet. Until the system does another layout pass, the view reports its width as zero.
In my opinion, you are better off leaving the TextView in the XML layout and simply making it invisible (android:visibility="invisible") until you need it, then make it visible prorammatically with setVisbility(View.VISIBLE). (Note that if you set it to be gone, it will also not be measured.)
For reference Karakuri pointed out the weaknesses and the path to follow to resolve them.
Extra code that was implemented for the listener is as follows.
IMAGE_CAPTURE_REQUESTED = true;
// New Listener
ViewTreeObserver vto = image_Layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
image_Layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
else
{
image_Layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
if (IMAGE_CAPTURE_REQUESTED) {
//int myId = text_Overlay.getId();
//Toast.makeText(MyActivity.this, "Text Overlay Width " + text_Overlay.getWidth() ,Toast.LENGTH_LONG).show();
overlayTextAndExportImage();
}
}
}); //End New Listener
The new overlayTextAndImportImage calls all the image creation routines after the layout has been redrawn.

How to make an ImageView overlay another View and hide it after a certain period of time?

I'm making a very simple Andriod app and I was wondering if I could get some help with my app.
I would like to show an ImageView over the full ListView (including the action bar) for 3 seconds, and then remove the ImageView (or hide it, anything), to go back to the list view.
How can this be done? I have tried a few things but it either breaks my code or doesn't show anything at all.
Thanks in advance everyone - let me know if you need any further explanation.
EDIT: As per the question below, I'd like the ImageView to be shown as soon as the ListView is shown, for 3 seconds, then disappear.
Allright. What you want is actually quite easy.
Simply create a RelativeLayout that contains a ListView and an ImageView above it.
Then inside your onCreate(...) method, you use a Handler and set the Visibility of the ImageView to GONE after 3 seconds.
Here is the layout.xml file:
<?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" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:scaleType="fitXY"
android:src="#drawable/your_image" />
</RelativeLayout>
And inside the onCreate(...) method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
final ImageView iv = (ImageView) findViewById(R.id.imageView1);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// EITHER HIDE IT IMMEDIATELY
iv.setVisibility(View.GONE);
// OR HIDE IT USING ANIMATION
hideImageAnimated(iv);
// DONT use both lines at the same time :)
}
}, 3000); // 3 seconds
}
In order to make things a bit smoother, you could use an AlphaAnimation on your ImageView:
public void hideImageAnimated(final ImageView iv) {
Animation alpha = new AlphaAnimation(1.0f, 0.0f);
alpha.setDuration(1000); // whatever duration you want
// add AnimationListener
alpha.setAnimationListener(new AnimationListener(){
#Override
public void onAnimationEnd(Animation arg0) {
iv.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation arg0) { }
#Override
public void onAnimationStart(Animation arg0) { }
});
iv.startAnimation(alpha);
}

Androids ExpandableListView - where to put the button listener for buttons that are children

I have been playing around a lot with the ExpandableListView and I cannot figure out where to add the button listeners for the button that will be the children in the view. I did manage to get a button listener working that uses getChildView() below, but it seems to be the same listener for all the buttons.
The best case scenario is that I would be able to implement the button listeners in the class that instantiates the ExpandableListAdapter class, and not have to put the listeners in the actual ExpandableListAdapter class. At this point I don't even know if that is possible
I have been experimenting with this tutorial/code: HERE
getChildView()
#Override
public View getChildView(int set_new, int child_position, boolean view, View view1, ViewGroup view_group1)
{
ChildHolder childHolder;
if (view1 == null)
{
view1 = LayoutInflater.from(info_context).inflate(R.layout.list_group_item_lv, null);
childHolder = new ChildHolder();
childHolder.section_btn = (Button)view1.findViewById(R.id.item_title);
view1.setTag(childHolder);
childHolder.section_btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(info_context, "button pushed", Toast.LENGTH_SHORT).show();
}
});
}else {
childHolder = (ChildHolder) view1.getTag();
}
childHolder.section_btn.setText(children_collection.get(set_new).GroupItemCollection.get(child_position).section);
Typeface tf = Typeface.createFromAsset(info_context.getAssets(), "fonts/AGENCYR.TTF");
childHolder.section_btn.setTypeface(tf);
return view1;
}
Any help would be much appreciated. Thank you and I will be standing by.
If the buttons are in the ExpandableListView, their listener needs to be in the adapter.
I'm not sure the thrust of your question, but if you are asking how do you relate the button to the contents of the child row, I can answer that. :p
I'll assume a somewhat simple child row layout for demonstration purposes.
child_row.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="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/ListItem1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:paddingLeft="7dip"
android:paddingRight="7dip"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/ListItem2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Then, to get the contents of the row when your button is pressed, you use the button to backtrack to the parent vieew and then get the necessary child views and their contents:
childHolder.section_btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
LinearLayout ll = (LinearLayout) v.getParent(); // get the view containing the button
TextView tv1 = (TextView) ll.findViewById(R.id.ListItem1); // get the reference to the first widget
TextView tv2 = (TextView) ll.findViewById(R.id.ListItem2); // get the reference to the second widget
String text1 = tv1.getText.toString(); // Get the contents of the first widget to a string
String text2 = tv2.getText.toString(); // Get the contents of the second widget to a string
}
});
If this isn't what you were looking for clarify your question and I'll take another shot at it.

Categories