Re-using same button for multiple rows in table layout - android

I have a Table layout that contains 3 rows with each row having a character name, current attributes and a button for re-rolling character attributes.
Like this:
Malarku s:10 i:15 c:5 [Re-Roll]
Zipak s:17 i:3 c:22 [Re-Roll]
Ambra s:6 i:24 c:7 [Re-Roll]
My problem is the button, because it has an id attached to it like this:
<Button
android:id="#+id/ButtonRollStats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_rollStats"
android:tag="#string/char1_name" />
And in my main activity code file, I have this:
Button rollStats = (Button) findViewById(R.id.ButtonRollStats);
rollStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddStatsView(view);
}
});
public void AddStatsView(View view) {
Intent intent = new Intent(this, DisplayStatsView.class);
String tag = view.getTag().toString();
intent.putExtra(EXTRA_NAME, tag);
startActivity(intent);
}
So I can't use the same button ID in each table row but I need the ID to find it and I don't want to have to use a different ID and method for each button when they all do the same thing(rolling stats).
How do I get around this issue?

Related

Multiple Image Buttons

I created an activity on android studio and I have put there something like 20 ImageButtons. I want to use it as on each click on an image it will move to a new activity. All of the Image Buttons are working on the same principle, my app is a game, and each image represents a level. I want to build one function that will be used on all buttons and will move the user to a new activity according to the data(the properties of the image button) and use that data on the new activity. Every level has its own activity and the main activity is the menu of the game.
Below is my code:
public ImageButton beatsCall; public void Beats(){ beatsCall=(ImageButton)findViewById(R.id.beats); beatsCall.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { Intent toy = new Intent(Levels.this,Beats.class); startActivity(toy); } }); }
You need to provide more information and code. However, you may want to try set a distinct onClickListener and then set all the imageButtons to that listener that will perform an action depending on the button clicked. For example, say you have 4 imageButtons and you want to perform a different action (in your case, start a new activity) for each different button click.
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
//Start activity 1 here, for example
Intent intent = new Intent(this, YourNewActivity1.class);
String message = v.getId().toString;
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
break;
case R.id.textView2:
//Start activity 2 here
break;
case R.id.textView3:
//Start activity 3 here
break;
case R.id.textView4:
//Start activity 4 here
}
}
};
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
button4.setOnClickListener(listener);
This is assuming you have the imageButtons set up in your layout file and you have them initialized in your activity.
In your new activity, you can get the message as such:
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
if (some condition with message){
do something
}
You may also check out this documentation for further information regarding intents.
Something like this? In your xml make your images clickable and give them ID's like this...
<ImageView
android:id="#+id/level_1_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
/>
Then call a function like this in your Activity's onCreate
private void setupButtons() {
findViewById(R.id.level_1_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplication(), LevelOne.class));
}
});
findViewById(R.id.level_2_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplication(), LevelTwo.class));
}
});
}
You could assign a tag via android:tag to each of your views and then use your single listener to switch on the view's tag to branch the behavior you want.

Android colouring app multiple background images

I am creating an android studio colouring app and need to have it so that the user can select which image they want to colour. I want it so that they click on an image button on one activity and this changes the background of the next activity that the button takes them to however I have no idea how to go about this. Any help would be greatly appreciated. Thankyou
From what I understand, you want to change the color of the next activity on button click of current activity. So, what you can do is:
button1.setOnClickListener(new View.OnClickListener{
#Override
public void onClick(View view){
Intent intent = new Intent(mContext, MyActivity2.class);
//Implement getDesiredColor to get the color according to your logic
intent.putExtra("color", getDesiredColor());
mContext.startActivity(intent);
}
});
In your second activity's onCreate
onCreate(...){
...
View rootLayout = //Initialize root layout here
Intent intent = getIntent();
if(intent.hasExtra("color")){
rootLayout.setBackgroundColor(intent.getExtra("color"));
}
...
}
Let me know in case you have any doubts.
UPDATE:
With drawable your code will become something like this:
button1.setOnClickListener(new View.OnClickListener{
#Override
public void onClick(View view){
Intent intent = new Intent(mContext, MyActivity2.class);
//Implement getDesiredDrawable to get the drawable according to your logic
intent.putExtra("drawable", getDesiredDrawable());
mContext.startActivity(intent);
}
});
In your second activity's onCreate
onCreate(...){
...
View rootLayout = //Initialize root layout here
Intent intent = getIntent();
if(intent.hasExtra("drawable")){
rootLayout.setBackground(intent.getExtra("drawable"));
//Or if you are using ImageView in your root layout to set the background image (I'm using Picasso here):
//Picasso.with(mContext).load(intent.getExtra("drawable")).into(myBackgroundImageView);
}
...
}
UPDATE 2:
You can have a hashmap mapping each imagebutton with a drawable.
e.g.
HashMap<Integer, Integer> mViewIdToDrawableMap = new HashMap<>();
mViewIdToDrawableMap.put(mImageButton1.getId(), R.drawable.image1);
mViewIdToDrawableMap.put(mImageButton2.getId(), R.drawable.image2);
mViewIdToDrawableMap.put(mImageButton3.getId(), R.drawable.image3);
public int getDesiredDrawable(View view){
return mViewIdToDrawableMap.get(view.getId());
}
How will you call this function:
button1.setOnClickListener(new View.OnClickListener{
#Override
public void onClick(View view){
Intent intent = new Intent(mContext, MyActivity2.class);
//Implement getDesiredDrawable to get the drawable according to your logic
intent.putExtra("drawable", getDesiredDrawable(view));
mContext.startActivity(intent);
}
});
Now, your last question what is rootLayout?
Lets say your activity2 where you want to show this image has somehitng like this as layyout:
<RelativeLayout>
<ImageView
...
android:id="id+/background_imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
...
/>
</RelativeLayout>
In your Activity2's onCreate, do somehting like this (after getting the drawable as I explained earlier):
//Here mBackgroundImageView is the background_imageview in your layout
Picasso.with(mContext).load(drawable).into(mBackgroundImageView);

Using setOnClickListener() in dynamically generated TextView

This is the TextView Layout.
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/trailer"
android:paddingTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"/>
This is the main root layout.
<LinearLayout
android:id="#+id/review_layout"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
And this piece of code add the textViews as childView of the above linear layout, based on total number of response from server.
#Override
public void addData(List<MovieVideoData> movieVideoDataList) {
trailerLinearLayout.removeAllViews();
List<TextView> textViews = new ArrayList<TextView>();
for (MovieVideoData movieVideoData:movieVideoDataList){
View view = getActivity().getLayoutInflater().inflate(R.layout.trailer_text_view,trailerLinearLayout,false);
((TextView)view.findViewById(R.id.trailer)).setText(movieVideoData.getName());
textViews.add(((TextView)view.findViewById(R.id.trailer)));
trailerLinearLayout.addView(view);
}
}
Now, for each TextView objects which was added in the Linear Layout, on the click of those i want to open an youtube video link specific to that textView.
I was wondering, how should i use the setOnClickListener() on each textView as id's of all are same.
Any suggestions, would be appreciated.
I added this piece of code and it's working fine.
private void watchYoutubeVideo(String key){
try{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + key));
startActivity(intent);
}catch (ActivityNotFoundException ex){
Intent intent=new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v="+key));
startActivity(intent);
}
}
textView.setText(movieVideoData.getName());
trailerLinearLayout.addView(view);
final String key = movieVideoData.getKey();
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
watchYoutubeVideo(key);
}
});
On click of each textview, it's opening its respective link on youtube, which is fine.
What i am not sure of is, after movieVideoDataList completes looping, and then on click of text view, how it remembers the specific key, as it inside the loop.
Any type of clarification on this would be appreciated.
I might be missing something, but why not just do it like this:
#Override
public void addData(List<MovieVideoData> movieVideoDataList) {
trailerLinearLayout.removeAllViews();
List<TextView> textViews = new ArrayList<TextView>();
for (MovieVideoData movieVideoData:movieVideoDataList){
View view = getActivity().getLayoutInflater().inflate(R.layout.trailer_text_view,trailerLinearLayout,false);
TextView tv = (TextView)view.findViewById(R.id.trailer);
tv.setText(movieVideoData.getName());
textViews.add(tv);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the url of your video and action you want to perform
}
});
trailerLinearLayout.addView(view);
}
}

how do i switch between sets of images?

Hi I'd like to create 2 sets of images where one set is displayed if the user selects something from a radio button and the other is displayed if the user selects the other radio button,
In truth I'm an amateur at this and it may not even be radio buttons that I want but its one set of images for a girl and another for a boy, any suggestions welcome
this is what I did... its inside an edittext but it shouldnt make any difference :
<EditText
android:id="#+id/exerciseInputFilter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="search..."
android:textColor="#android:color/holo_blue_light" />
<ImageView
android:id="#+id/drillListSearchImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/exerciseInputFilter"
android:layout_alignParentRight="true"
android:src="#drawable/search_white" />
in the xml for example... frame is also possible...
and in code...
SearchImage = (ImageView) findViewById(R.id.drillListSearchImage);
SearchImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!filterText.getText().equals(null)) {
filterText.setText("");
SearchImage.setImageResource(R.drawable.search_white);
}
return false;
}
});
so just create 1 image view and then on touch do something...
if you want to use a radio or checkbox its the same principle... on item click... set imageview to whatever you want...
rd2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rd1.setChecked(false);
SearchImage.setImageResource(R.drawable.search_white);
}
});
for example... does this answer your question?
Edit
after reading your comment (which wasnt understandable from your original question)... what you want is just to pass information between activities to do that use this:
Activity A:
create a boolean and a 2 check or radios and
CheckBox maleBox = (CheckBox) findViewById(R.id.Male);
maleBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
isMale = true;
isFemale = false;
femaleBox.setChecked(false);
}
}
});
you can do the same for female if you want several radios or checkboxs... then...you pass the information to activity two... like so:
intent = new Intent(whateverclass.this, whoeverclass.class);
intent.putExtra("Gender", isMale);
startActivity(intent);
now you can read it in activity two with:
if (getIntent().getBooleanExtra("Gender", false)) {
// set Images or buttons or what ever...(like i showed you above)
SetImage1.setImageResource(R.drawable.boy);
.
.
.
}
you can also use bundle to get your variables...
Intent intent = new Intent();
intent = getIntent();
Bundle bundle = intent.getExtras();
then just get the boolean...

TableLayout, Different Button actions depending on data in TableRow

I have the following problem:
I have a TableLayout along with several TableRows, which are dynamically created.
On the right side of every row I create a button, which should call another activity.
Now I want to pass some information with intent.putExtra(). In this case I want so pass the row number, which is also the first information in the row.
Here is a picture of the current state:
This is how I create the buttons during run-time (in a loop):
Button b1 = new Button (this, null, android.R.attr.buttonStyleSmall);
b1.setId(1000+grButtonId);
b1.setText("Request GR");
b1.setLayoutParams(params);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Some code, taken out for clarity
// See next code snippet
}
});
grButtonId++;
tr.addView(b1);
My idea so far is to use the id of the button (of course), and get the line number by the value of grButtonId.
Now comes my problem, let's have a detailed look at my onClickmethod:
#Override
public void onClick(View view) {
// finished is true, as soon as GRRequest has recieved the data
if(!finished & !dataRequested){
new GRRequest().execute(getIntent().getLongExtra("poNr", 0),(long)view.getId());
b1.setText("Show GR");
Log.d("DataList", detailList.toString());
dataRequested=true;
}
else{
if (dataRequested){
b1.setText("Show GR");
}
Intent intent = new Intent(DataTableCreater.this, GRTableCreater.class);
intent.putExtra("lineNr",view.getId());
intent.putExtra("dataList", detailList);
startActivity(intent);
}
}
When I request my data, the button I clicked on gets set to "Show GR" , as intended. The other buttons stay on "Request GR", this is also fine. But now I want these Buttons to Change to "Show GR" when tapped first and on second tap start the activity.
By now, the buttons change to "Show GR" and directly start the activity.
What would be a solution, to make this work?
Create a boolean Array clickedOnce[] = new boolean[grButtonId+1] one field for every Button.
Then have this
public void onClick(View view) {
if(!finished){
new GRRequest().execute(getIntent().getLongExtra("poNr", 0),(long)view.getId());
b1.setText("Show GR");
Log.d("DataList", detailList.toString());
clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]=true; //sets the clickedOnce for this button to true, substring(1,4) is needed to cancle the leading 1 from the id
}
else{
//Checks, if the button was clicked once
if (!clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]){
b1.setText("Show GR");
clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]=true;
}
else{
Intent intent = new Intent(DataTableCreater.this, GRTableCreater.class);
intent.putExtra("lineNr",view.getId());
intent.putExtra("dataList", detailList);
startActivity(intent);
}
}
}

Categories

Resources