how to get R.id's in the int array? - android

I want to get the id's of my imageviews in my ObjectsClass which are in level1.xml and I have inflated this layout in GamePlayActivity...MY ObjectClass is not activity then how to get array of id's in that class ...here is my level.xml say there are 15 ImageView I have just shown few ....
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/gmw_01"
android:onClick="onClick"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/relativeLayout1" >
<ImageView
android:onClick="objectClick"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/imageView1"
android:src="#drawable/bb01"
android:layout_marginLeft="998dp"
android:layout_marginTop="593dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"/>
<ImageView
android:onClick="objectClick"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/imageView2"
android:src="#drawable/bb02"
android:layout_marginLeft="20dp"
android:layout_marginTop="39dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"/>
<ImageView
android:onClick="objectClick"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/imageView3"
android:src="#drawable/bb03"
android:layout_marginLeft="497dp"
android:layout_marginTop="153dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"/>
and here is my GameplayActivity
public class GamePlayActivity extends Activity {
static int ObjectsFound;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameplay);
// ViewGroup where n number of view is going to added
ViewGroup layout= (ViewGroup) findViewById(R.id.GamePlayScreen);
// inflating the layout depending on the level
View level = View.inflate(this, LevelSelectionActivity.levelscreen, null);
** getRandom(); // here I want to call that random because this should be done before my level is added on the view**
// adding level bg for the respective selected level
layout.addView(level);
}
public void objectClick(View objectClicked)
{
Toast msg;
int Object = objectClicked.getId();
ImageView img= (ImageView)findViewById(objectClicked.getId());
switch (Object) {
case R.id.imageView1:
img.setVisibility(View.INVISIBLE);
msg = Toast.makeText(GamePlayActivity.this, "Bubble Found", Toast.LENGTH_SHORT);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
break;
}
}
and the ObjectClass
public class Objects {
int ObectId[];
Objects(Context context)
{
super();
for(int i=0;i<15;++i)
{
**ObectId[i]=R.id.;** // what to get it over here ? ? ?
}
}
public void randomize() {
Random generator = new Random();
for(int i = 0; i<8 ; i++) {
while(true) {
**View v = findViewById(generator.nextInt(Objectid.length));**
if(!v.isClickable()) {
v.setClickable(false);
break;
}
}
}
}
}
at the end I want random number of objects to be unclickable i.e. out of 15 objects everytime user can have only 8 objects clickable on the screen so before my level starts i.e. before I inflate in my gameplayActivity as seen above I want to get random 8 clickable and vice versa...
Adding to that it should work for all level ...right now I have one level1.xml how to achieve it for all levels... do i need to give same id's of image view in all layout ?

Sure you can, all you need to do is make the ImageView with the same id name, then you can always access them with the same int id.
Don't forget to re-init them after load new layout.

try some thing like this
int resA = getResources().getIdentifier("your image view", "your layout", getPackageName());
hope this help..

Are there any views inside that RelativeLayout besides each ImageView you're interested in? If not, just use the getChildCount() and getChildAt() methods on the layout to obtain the views you need. Any ViewGroup already stores its children in an array, so there's no reason to duplicate the behavior if those are the only views contained there:
//Somewhere in your code get a reference to the layout
RelativeLayout layout = (RelativeLayout)findViewById(R.id.relativeLayout1);
//Then, update your view selection line like so
**View v = layout.getChildAt(generator.nextInt(layout.getChildCount()));**
HTH

Related

android change image view inside list view when button is clicked

I know that this question might be a duplicate of another question but i tried to follow what was suggested in solutions to similar questions without any success. I am relatively new to android so please kindly point me in the right direction.
Scenario:
I have a list view that has a custom layout file containing a small image and a text view. The list view displays all items as intended but what I want to do is as follows:
When a button is clicked, a condition is evaluated and if the result is true, i want to change the default image to another one. I am aware that I have to perform the image switching in the get view method that I have to override.
public View getView(int position, View convertView, ViewGroup parent) {
View itemView=convertView;
if (itemView==null) {
itemView=getLayoutInflater().inflate(R.layout.check_list_view, parent, false);
}
MailObject currentMailObject=mailList.get(position);
ImageView ivCurrentMail=(ImageView)itemView.findViewById(R.id.ivMailIcon);
if (mailList.get(position).isScanned()) {
ivCurrentMail.setImageResource(R.drawable.ic_mail_scanned);
}
return itemView;
}
The code for the button is:
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), scanResult, Toast.LENGTH_LONG).show();
if(!scannedMails.contains(scanResult))
{
scannedMails.add(scanResult);
for (int i = 0; i < mailList.size(); i++) {
if (mailList.get(i).getCode().equalsIgnoreCase(scanResult)) {
int position=i;
mailList.get(i).setScanned(true);
ImageView ivCurrent = (ImageView) lvMails.getAdapter().getView(position, null, null).findViewById(R.id.ivMailIcon);
ivCurrent.setImageResource(R.drawable.ic_mail_scanned);
lvMails.invalidateViews();
}
}
}
}
});
The XML file for a list view item is as follows:
<ImageView
android:id="#+id/ivMailIcon"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/ic_mail_not_scanned" />
<TextView
android:id="#+id/tvMailItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_toRightOf="#+id/ivMailIcon"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
I did test if the condition evaluates as it should by displaying a Toast message on list view item click and the results were positive but the image just does not change. Please let me know where I went wrong or missed something. Thanks
You're setting the same image twice. In both cases, you use the setImageResource() method for the ImageView that points to R.id.ivMailIcon to set the drawable as R.drawable.ic_mail_scanned.
You are probably "setting" to image again correctly on a click, but since it's the same image, it won't appear to change.

android - some views are not "visible" after activity restart

Hello Android developers,
i'm facing a strange behaviour of some views after activity restart - there are some views, which are not "visible", but they are layouted and react on Touch actions.
I'm trying to keep the application follow Android lifetime guide. I drop the Activity to background and let system to close my activity. Then I navigate back to my activity, which is recreated. There is no problem with data to be corrupted (saved in db with every change made), but the views are. There are some properly shown, but everything inside TableView, which is inside ScrollView, is not visible. If I call getVisibility() on any of not shown views, i get that it is visible. As I mentioned above, views are not "visible", but react on Touch and scroll events, like they were properly shown.
This is also hard (impossible) to debug, cause when the app is closed, debbuger is disconnected. But anyway, recreation follows the same methods callback - onCreate(), onStart(), onResume(), so once created, why there's problem other time? The only difference to me is that there is a null Bundle in onCreate(Bundle) when Activity is newly created and not null when it is recreated by system. If the activity is only stopped (in background) but not closed by system, everything works fine.
I also tryed to override onSaveInstanceState() and onRestoreInstanceState() with nothing to be saved and restored (no call to super implementation), but it had no effect.
I'm using Android 4.1.1 and emulator 2.1.
Does anyone have any idea?
Thanks Ales
Here are (links to) screenshots to figure it out better:
Before activity is closed by system
After activity is recreated
Here are the layout files:
<!-- Header -->
<LinearLayout
android:id="#+id/startlistHeaderLayout" xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView android:id="#+id/textStartlistName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="1"
android:gravity="left"
android:text=""
/>
<TextView android:id="#+id/textStarttime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="1"
android:gravity="right"
android:text=""
android:layout_weight="1"
/>
</LinearLayout>
<!-- Results -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/resultsScrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:saveEnabled="false"
>
<TableLayout
android:id="#id/timingLapTableLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="2"
android:shrinkColumns="2"
android:saveEnabled="false"
>
<!-- rows are added in code -->
</TableLayout>
</ScrollView>
</LinearLayout>
<!-- R.layout.timing_row -->
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/timingTableRow"
android:saveEnabled="false"
>
<TextView
android:id="#id/textTimingPosition"
android:text=""
android:gravity="right"
android:paddingLeft="4dip"
android:saveEnabled="false"
/>
<TextView
android:id="#id/textTimingBib"
android:text=""
android:gravity="right"
android:paddingLeft="1dip"
android:saveEnabled="false"
/>
<TextView
android:id="#id/textTimingName"
android:text=""
android:lines="1"
android:ellipsize="end"
android:gravity="left"
android:paddingLeft="1dip"
android:paddingRight="5dip"
android:saveEnabled="false"
/>
<TextView
android:id="#id/textTimingBehind1"
android:text=""
android:gravity="right"
android:paddingRight="5dip"
android:saveEnabled="false"
/>
<TextView
android:id="#id/textTimingBehind2"
android:text=""
android:gravity="right"
android:paddingRight="5dip"
android:saveEnabled="false"
/>
</TableRow>
Here is part of Activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
loadPreferencesTimingTheme();
if (ownTheme) {
this.setTheme(theme);
} else {
this.setTheme(MainActivity.theme);
}
}
protected void onStart() {
super.onStart();
View lapView;
View v;
int sid;
setContentView(R.layout.startlist_edit);
sid = getIntent().getIntExtra(TimingActivity.STARTLIST_ID, -1);
if (sid == -1) {
Toast.makeText(this, "Sorry, could not load startlist.", Toast.LENGTH_LONG);
this.finish();
return;
}
tdb = new TimingDB(this);
sl = tdb.getStartlist(sid); // get Startlist from db into memory
// hide unnecessary columns
v = findViewById(R.id.timingLapTableLayout);
((TableLayout) v).setColumnCollapsed(0, true);
loadStartlist(sl); // inflate rows with startlist data and set listeners
// load the preferences and set preferences listener
loadPreferences();
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(prefsChangeListener);
}
public void onStop() {
super.onStop();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(prefsChangeListener);
if (tdb != null) tdb.close();
}
protected void onSaveInstanceState (Bundle outState) {
// super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState (Bundle savedInstanceState) {
// super.onRestoreInstanceState(savedInstanceState);
}
protected void onDestroy() {
super.onDestroy();
if (tdb != null) tdb.close();
}
private void loadStartlist(StartList sl) {
// set startlist name & time
View v = findViewById(R.id.textStarttime);
((TextView) v).setText(SimpleDateFormats.ddmmyyyyhhmmss.format(new Date(sl.getStartTime())));
v = findViewById(R.id.textStartlistName);
((TextView) v).setText(sl.getName());
// set header onclicklistener
v = findViewById(R.id.startlistHeaderLayout);
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// show dialog to change startlist name and time
Bundle args = new Bundle();
args.putString(KEY_NAME, ((TextView) findViewById(R.id.textStartlistName)).getText().toString());
args.putString(KEY_STTIME, ((TextView) v.findViewById(R.id.textStarttime)).getText().toString());
if (Build.VERSION.SDK_INT < 8) {
dialogBundle = args;
showDialog(DIALOG_EDIT_STARTLIST);
} else {
showDialog(DIALOG_EDIT_STARTLIST, args);
}
}
});
// add competitors to startlist
int cnt = sl.getCompetitorsCount();
for (int i = 0; i < cnt; i++) {
Competitor c = sl.getCompetitorByIndex(i);
appendStartlistRow(c);
}
}
public void appendStartlistRow(final Competitor c) {
TableRow inflatedView = (TableRow) getLayoutInflater().inflate(R.layout.timing_row, null);
inflatedView.setTag(TAG_COMPETITOR, c);
inflatedView.setTag(new Integer(c.getBib()));
inflatedView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TableLayout tl = (TableLayout) findViewById(R.id.timingLapTableLayout);
Bundle args = new Bundle();
args.putInt(KEY_INDEX, tl.indexOfChild(v));
if (Build.VERSION.SDK_INT < 8) {
dialogBundle = args;
showDialog(DIALOG_EDIT_COMPETITOR);
} else {
showDialog(DIALOG_EDIT_COMPETITOR, args);
}
}
});
// set up texts
TextView text = (TextView) inflatedView.findViewById(R.id.textTimingBib);
text.setText(c.getBib() + "");
text = (TextView) inflatedView.findViewById(R.id.textTimingName);
text.setText(c.getName());
text = (TextView) inflatedView.findViewById(R.id.textTimingBehind1);
text.setText(getFormatedStartTime(sl, c, Settings.STARTTIME_ABSOLUTE));
text = (TextView) inflatedView.findViewById(R.id.textTimingBehind2);
text.setText(getFormatedStartTime(sl, c, Settings.STARTTIME_RELATIVE));
// append the row
appendStartlistRow((ViewGroup) inflatedView);
}
public void appendStartlistRow(ViewGroup row) {
// set background and text colors
if (((((Integer) row.getTag()).intValue()) % 2) == Defs.VIEW_EVEN) {
row.setBackgroundColor(Defs.COLOR_BACKGROUND_EVEN);
for (int j = 0; j < row.getChildCount(); j++) {
((TextView) (row.getChildAt(j))).setTextColor(Defs.COLOR_TEXT_EVEN);
}
} else {
row.setBackgroundColor(Defs.COLOR_BACKGROUND_ODD);
for (int j = 0; j < row.getChildCount(); j++) {
((TextView) (row.getChildAt(j))).setTextColor(Defs.COLOR_TEXT_ODD);
}
}
((TableLayout) findViewById(R.id.timingLapTableLayout)).addView(row);
}
Defs.java:
public class Defs {
protected static final int VIEW_EVEN = 0;
protected static final int VIEW_ODD = 1;
protected static int COLOR_BACKGROUND_EVEN;
protected static int COLOR_BACKGROUND_ODD;
protected static int COLOR_BACKGROUND_SELECTED;
protected static int COLOR_BACKGROUND_SPYED;
protected static int COLOR_TEXT_ODD;
protected static int COLOR_TEXT_EVEN;
protected static int COLOR_TEXT_SELECTED;
protected static int COLOR_TEXT_SPYED;
private static boolean isInitialized = false;
protected static void init(Context c) {
if (isInitialized) return;
COLOR_BACKGROUND_EVEN = c.getResources().getColor(R.color.background_darker);
COLOR_BACKGROUND_ODD = c.getResources().getColor(R.color.background_lighter);
COLOR_BACKGROUND_SELECTED = c.getResources().getColor(R.color.background_selected);
COLOR_BACKGROUND_SPYED = c.getResources().getColor(R.color.background_spyed);
COLOR_TEXT_ODD = c.getResources().getColor(R.color.text_lighter);
COLOR_TEXT_EVEN = c.getResources().getColor(R.color.text_darker);
COLOR_TEXT_SELECTED = c.getResources().getColor(R.color.text_selected);
COLOR_TEXT_SPYED = c.getResources().getColor(R.color.text_spyed);
isInitialized = true;
}
}
Without any code it's next to impossible to say much about the problem itself. But I did want to say (would fit better as a comment but can't do it yet) that for a long list (like yours seems to be based on the screenshots) using an actual ListView with a custom ArrayAdapter might be a better solution. ListView re-uses views when scrolled thus reducing unnecessary view creation. Also, once you learn how to use the ListView, you'll probably find it easier than adding table rows manually. If those aren't familiar to you, check a tutorial here:
http://www.vogella.com/articles/AndroidListView/article.html
And if you decide to change from tables to a ListView, maybe the problem (whatever it is) disappears as well. You never know. :)

How to scroll a HorizontalScrollView on button click in android?

I have horizontal scrollview in my android app with Next and Previous buttons.I want to show the these buttons only when the scollview needs scrolling.ie,width of scrollview content exceeds display width.Also want to hide previous and Next buttons when reaching first and last items respectively.How to to next/previous items when click on these buttons?
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff" >
<Button
android:id="#+id/btnPrevoius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Previous"
android:visibility="gone" />
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_toLeftOf="#+id/btnNext"
android:layout_toRightOf="#+id/btnPrevoius"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Next"
android:visibility="gone" />
</RelativeLayout>
activity
public class SampleActivity extends Activity {
private static LinearLayout linearLayout;
private static HorizontalScrollView horizontalScrollView;
private static Button btnPrevious;
private static Button btnNext;
private static int displayWidth = 0;
private static int arrowWidth = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView1);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
btnPrevious = (Button) findViewById(R.id.btnPrevoius);
btnNext = (Button) findViewById(R.id.btnNext);
for (int i = 0; i < 15; i++) {
Button button = new Button(this);
button.setTag(i);
button.setText("---");
linearLayout.addView(button);
}
ViewTreeObserver vto = linearLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewTreeObserver obs = linearLayout.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
Display display = getWindowManager().getDefaultDisplay();
displayWidth = display.getWidth();
if (linearLayout.getMeasuredWidth() > (displayWidth - 40)) {
btnPrevious.setVisibility(View.VISIBLE);
btnNext.setVisibility(View.VISIBLE);
}
}
});
btnPrevious.setOnClickListener(listnerLeftArrowButton);
horizontalScrollView.setOnTouchListener(listenerScrollViewTouch);
}
private OnTouchListener listenerScrollViewTouch = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
showHideViews();
return false;
}
};
private OnClickListener listnerLeftArrowButton = new OnClickListener() {
#Override
public void onClick(View v) {
horizontalScrollView.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0, 0));
}
};
public static void showHideViews() {
int maxScrollX = horizontalScrollView.getChildAt(0).getMeasuredWidth()- displayWidth;
Log.e("TestProjectActivity", "scroll X = " +horizontalScrollView.getScrollX() );
Log.i("TestProjectActivity", "scroll Width = " +horizontalScrollView.getMeasuredWidth() );
Log.d("TestProjectActivity", "Max scroll X = " + maxScrollX);
if (horizontalScrollView.getScrollX() == 0) {
hideLeftArrow();
} else {
showLeftArrow();
}
if (horizontalScrollView.getScrollX() == maxScrollX) {
showRightArrow();
} else {
//hideRightArrow();
}
}
private static void hideLeftArrow() {
btnPrevious.setVisibility(View.GONE);
}
private static void showLeftArrow() {
btnPrevious.setVisibility(View.VISIBLE);
}
private static void hideRightArrow() {
btnNext.setVisibility(View.GONE);
}
private static void showRightArrow() {
btnNext.setVisibility(View.VISIBLE);
}
}
The 'maxScrollX' value is not correct for me.How to find maximum scrollvalue for this?
Thanks in Advance
This might come a bit late, but for anyone out there that will face this problem I suggest alternative solution(s).
First, use different component than HorizontalScrollView. Here are the options:
OPTION 1: Horizontal ListView - add this class to your project (create a separate package, something like com.yourproject.widgets). Also you'll need to create custom Adapter, see how that's done in this example. I suggest you create separate adapter class (exp. HorizontalListViewAdapter) and put it in already created com.yourproject.widgets package.
add this widget to your layout in the xml (put it between buttons that need to mimic the scrolling behavior) you'll need to add something like:
<com.yourproject.widgets.HorizontalListView
android:id="#+id/hList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
reference this (along with the buttons) in the Activity/Fragment that utilizes the widget
HorizontalListView mHList = (HorizontalListView) findViewById (R.id.hList);
Button bPrevoius = (Button) findViewById (R.id.btnPrevoius);
Button bNext = (Button) findViewById (R.id.btnNext);
add onClickListeners to the Buttons. Use the scrollTo() function predefined in the HorizontalListView widget. As you can see in the code, it takes int dp value to scroll. Add positive values if you want to scroll in right (next), and use negative values if you want to scroll in left (previous):
bPrevoius.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//value 500 is arbitrarily given. if you want to achieve
//element-by-element scroll you should get the width of the
//previous element dynamically or if the elements of the
//list have uniform width just put that value instead
mHList.scrollTo(-500);
//if it's the first/last element you can bPrevoius.setEnabled(false)
}
});
bNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mHList.scrollTo(500);
}
});
OPTION 2: More up to date solution to this issue can be the new widget RecyclerView introduced in Android L (addition of android:scrollbars="vertical" seems that would do the trick; other than that should have conventional ListView behavior). For more info check the official documentation.
devu
Plz have a look at the following links
1) http://android-er.blogspot.in/2012/07/implement-gallery-like.html
2) http://androiddreamers.blogspot.in/2012/09/horizontal-scroll-view-example.html
3)http://code.google.com/p/mobyfactory-uiwidgets-android/
Let me know if u r facing any issues
Thanks
In titanium appcelerator, you can do this using scrollableView
var scrollableView = Ti.UI.createScrollableView({
showPagingControl:true,
scrollingEnabled: true,
top: 360
});
Then, you can run a loop of all images or any content that you have, and add them to this view.
for(loop) {
eval("var view"+i+"=Ti.UI.createView();");
profile_image = Ti.UI.createImageView({
image: result[0]['profile_image'],
left:15,
width:82,
height:104,
top: 0
});
eval("view"+i+".add(profile_image);");
eval("scrollableView.addView(view"+i+");");
}
mywin.add(scrollableView);

Getting Array index on item click

I have created an Android RSS Reader App.I have a text marquee in my android app.Iam fetching RSS feed and store RSS title as an array.Iam setting this array as the marque text.Check the code,
String MarqueeStr="";
TextView flashnews;
for (int i = 0; i < nl.getLength(); i++) {
MarqueeStr = MarqueeStr +" | "+ Headlines.Title[i];
}
flashnews.setText(MarqueeStr);
Now I have to set an onclick listener for my marquee, so that user can view detailed description of title which they are clicked.I know how to set it.But my problem is, how can i get the array index of clicked string in the marquee text when a user click on the marquee?
here is my XML layout,
<TextView
android:id="#+id/flashs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:layout_marginLeft="70dp"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:textColor="#e7e7e7" />
screen shote here..
can you see that "Latest News"? its my marquee text
I think that will only be possible if you will create your textviews dynamically and set id for them. like if you are having 10 news link then use 10 textviews
TextView txt = null;
View.OnClickListener marquee_click = new View.OnClickListener() {
#Override
public void onClick(View v) {
int selected_item = v.getTag();
switch (selected_item) {
case 0:
break;
case 1:
break;
case 2:
break;
default:
break;
}
}
};
LinearLayout news_text_layout = new LinearLayout(getApplicationContext());
news_text_layout.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i < 10; i++) {
txt = new TextView(getApplicationContext());
txt.setTag(i); // OR txt.setId(i);
txt.setText("new " + i);
txt.setOnClickListener(marquee_click);
news_text_layout.addView(txt);
}
// ADD YOUR LINEAR LAYOUT ON WHICH YOU HAVE ADDED ALL TEXT VIEW IN YOUR LISTVIEW FOOTER.
// NOW PERFORM SAME ANIMATION OR TRICK ON LINEAR LAYOUT WHICH YOU WERE PERFORMING ON marquee text.
Hope it can help you...
You can add every FlashNews as a dynamically created TextView. And you can put all of these in
one HorizontalScrollView. And set their listeners seperatly.
For marquee function, you can programmatically scroll the horizontalView within your code.
I dont know if it's possible to make it with your idea. (Actually it can be done, but it will contain pain i guess)
for animation look at this i have just created.
Create new project then add class and xml file which i am giving.
public class Test_stflowActivity extends Activity {
LinearLayout ll = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
final TranslateAnimation ts = new TranslateAnimation(200, -100, 0, 0);
ll.setAnimation(ts);
ts.setDuration(5000);
TextView tv = new TextView(getApplicationContext());
tv.setText("*bharat sharma*");
tv.setTextSize(30);
ll.addView(tv);
ll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ll.startAnimation(ts);
}
});
}
}
this is xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" >
</LinearLayout>
</RelativeLayout>
it is working for me
if you use a ListView with an adapter, (which you should), you can use the getItem(int position) function to get the specific item.

How to change Resource of ImageView in ListView which is set to a SimpleCursorAdapter

I'm trying to make an HighscoreList for my App.
This List is based on a SQL Database. Save the name and the score is working very well.
The ListView is based on this row xml File:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/NAME_CELL"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:textSize="20dip" />
<TextView android:id="#+id/SCORE_CELL"
android:layout_width="20dip"
android:layout_height="wrap_content"
android:textSize="20dip" />
<ImageView android:id="#+id/PICTURE_CELL"
android:layout_width="50dip"
android:layout_height="20dip"
android:src="#drawable/no_picture" />
And I want that for example if the player reaches a score of 10 the PICTURE_CELL ImageView should show an Image.
For now I have a Cursor which is going through the Database and looks for the Highscores:
public void drawPictures()
{
if (dbCursor.moveToFirst()) {
do
{
if(dbCursor.getInt(2)<=4)
{
Log.d(TAG, "no picture");
}
else if((dbCursor.getInt(2) > 4) && (dbCursor.getInt(2) <= 9))
{
Log.d(TAG, "picture1");
}
else if((dbCursor.getInt(2) > 9) && (dbCursor.getInt(2) <= 19))
{
Log.d(TAG, "picture2");
}
else if(dbCursor.getInt(2) > 20)
{
Log.d(TAG, "picture3");
}
}
while (dbCursor.moveToNext());
But I have no Idea how I can change the Resource of every ImageView in each row.
Please help me, this is killing me for days!
Thanks!
You have to create a custom adapter to do this kind of processing. A simple cursor will not do that for you.
Sample:
http://android.vexedlogic.com/2011/04/02/android-lists-listactivity-and-listview-ii-%E2%80%93-custom-adapter-and-list-item-view/
While this example uses an ArrayAdapter, it doesn't matter that much to the processs. The process s the same. You must create your own custom adapter. Once you create your custom cursor class, then you will override the getView(...) method with your preprocessing logic.
Explanation of comment
In your database helper:
public static final int COL_NAME = 2;
In your code,
dbCursor.getInt([Database Helper Object].COL_NAME)
I don't fully follow your drawPictures method but I would suggest you make your query include an ORDER keyword so your values are ordered rather than searching.
Then in the adapter getView method use getCursor().getInt(<score column>) and check if the score is greater than 10
if(score > 10)
If it is you can do:
ImageView imageView = ( ImageView ) view.findViewById( R.id.PICTURE_CELL )
then call:
// where drawable is whatever image you would like to present
imageView.setImageDrawable(Drawable drawable)
UPDATE from comments
Your SimpleCursorAdapter is a sublcass of CursorAdapter which does have getView, you just need to extend your SimpleCursorAdapter and add the method below.
You need to over ride this methods like so:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int score = dbCursor.getInt(<score column>)
// You might need to call moveToPosition(position) or maybe you should use getItem(position) I have not tested it
if(score > 10) {
ImageView imageView = ( ImageView ) view.findViewById( R.id.PICTURE_CELL )
// where drawable is whatever image you would like to present
imageView.setImageDrawable(Drawable drawable)
}
}

Categories

Resources