How to programmatically create an object (i..: a textView) inside a CardView? - java

I want to make a newsletter app with the feature to make posts yourself.
I'm trying to makr a code for a button and I am stuck at the one moment. I don't know how to set a position for a new textView in the new cardView.
Here is a piece of code from MainActivity.java
package com.example.rame956.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScrollView scrollView = new ScrollView(this);
}
//<...>
public void CreateNewPost(View view){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
CardView card = new CardView(this);
TextView text = new TextView(this);
ImageView image = new ImageView(this);
}
}
Sorry if it's a dumb qustion. I'm new in android developing.

For starters, I'd assume you would at least have a button inside your MainActivity which will trigger the process of creating a cardview. Therefore, to answer your question, I'll create a brand new card view programmatically from scratch. Take the elements which you need out of it i.e. textview, buttons and so on.
// Wiring in my 2 main aspects relativeLayout + Button
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
button = (Button) findViewById(R.id.btn);
//my trigger but in your case, it can be anything
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CardView card = new CardView(mContext);
// Set the CardView layoutParams
LayoutParams layoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
card.setLayoutParams(layoutParams );
// Setting different attributes
card.setRadius(9);
card.setContentPadding(15, 15, 15, 15);
card.setCardBackgroundColor(Color.parseColor("#FFC6D6C3"));
card.setMaxCardElevation(15);
card.setCardElevation(9);
// Initialize a new TextView to put in CardView
TextView tv = new TextView(mContext);
tv.setLayoutParams(layoutParams );
tv.setText("My CardView");
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
tv.setTextColor(Color.RED);
// Put the TextView inside CardView
card.addView(tv);
// Finally, add the CardView in root layout
relativeLayout.addView(card);
}
});
One thing to note here is the relativeLayout at the end of the function. You will need to have a parent layout in which you'll be placing your cardview. And of course, the attributes can be modified to your needs i.e. settext, backgroundcolour and so on.
If you simply want to insert a TextView to a pre-existing CardView in your xml. It'll be the same concept.
card = (CardView)findViewById(R.id.cardView);
//generate your textview as above....
card.addView(textView);

Related

Aligning Elements in a CardView Programatically

I'm working on a custom form activity that gives all elements their own CardView. When I add elements to a LinearLayout and add that to the CardView it works just fine, but when I try to arrange them in a RelativeLayout they don't seem to go where I want them. Here is a picture that shows the bug: Screenshot. The top is the error I'm getting, the bottom is what I'm trying to get it to look like.
Here's my current code:
package com.cpjd.roblu.activities;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.cpjd.roblu.R;
import java.util.ArrayList;
public class TeamViewer extends Activity {
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
// adapters
LinearLayout layout;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_viewer);
layout = (LinearLayout) findViewById(R.id.team_viewer_cards);
addEditText();
addEditText();
addEditText();
addEditText();
addBoolean();
}
private void addBoolean() {
RadioGroup group = new RadioGroup(this);
RadioButton b = new RadioButton(this);
b.setText("Yes");
RadioButton b2 = new RadioButton(this);
b2.setText("No");
group.addView(b);
group.addView(b2);
TextView t = new TextView(this);
t.setText("Boolean");
RelativeLayout layout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
group.setLayoutParams(params);
layout.addView(t);
layout.addView(group);
addCard(layout);
}
private void addCard(View layout) {
CardView card = new CardView(getApplicationContext());
card.setLayoutParams(params);
card.setRadius(0);
card.setContentPadding(15, 15, 15, 15);
card.setUseCompatPadding(true);
card.setCardBackgroundColor(Color.DKGRAY);
card.setCardElevation(5);
card.addView(layout);
this.layout.addView(card);
}
}
In the LayoutParams you specified for the group, arguments should be flipped (first constructor argument is width, second - height, not the opposite):
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
Otherwise group takes full width of the parent and any horizontal alignment doesn't make any sense. Also try to avoid using getApplicationContext() when creating the views, because otherwise you get theme from the app, which may differ from the one you are using in Activity.
And the last: specify LayoutParams for all the views you create in runtime as well. For example, for the layout:
layout.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
Keep in mind, that LayoutParams is mandatory piece of information for every view. If not specified, then view will use the default one.

why does it not follow the if statement

package com.example.firstapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
import static com.example.firstapplication.MainActivity.EXTRA_MESSAGE;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
if (EXTRA_MESSAGE.equals ("h")) {
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}else {
TextView textView = new TextView(this);
textView.setTextSize(4);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
}
if i type in h on my thing the output should be h in size 40 font and it should work only for h, but when is type in h or anything else it comes out in size 4, help, what do i do
I think instead of EXTRA_MESSAGE, do you want to check with message string?
Else you can use the debug mode in Android Studio to know what variables contains.

Multiple activities make changes in a single layout

I'm just started to make my first android app and I'm trying to get more familiar with the basic principles of android developing. So, in no time my MainActivity exploded with lines of code. To make my code more maintainable, i'm trying to put pieces of code in different activities. Also according to the design principles of android: Don't Overload a Single Activity Screen
Now I'm struggling to use different activities with a single XML layout. I found some similar cases here like: this one But i'm also reading here that I should use fragments. I can't see how to work this out properly.
The specific problem I encounter with my code is that the second activity should change the background of the imageview to normal with the setImageResource, but it doesn't.
My code:
package com.test.scores;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends Activity implements View.OnClickListener {
private ImageButton btn1, btn2;
int varMinusScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(this);
btn2 = (ImageButton) findViewById(R.id.btn2);
btn2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
varMinusScore = 1;
startActivity(new Intent(getApplicationContext(), ResetImageResources.class));
btn1.setImageResource(R.drawable.btn01p);
}
switch (v.getId()) {
case R.id.btn2:
varMinusScore = 2;
startActivity(new Intent(getApplicationContext(), ResetImageResources.class));
btn2.setImageResource(R.drawable.btn02p);
}
}
}
And the second activity:
package com.test.scores;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
public class ResetImageResources extends Activity {
private ImageButton btn1, btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (ImageButton) findViewById(R.id.btn1);
btn2 = (ImageButton) findViewById(R.id.btn2);
btn1.setImageResource(R.drawable.btn01);
btn2.setImageResource(R.drawable.btn02);
finish();
}
}
Activities are absolutely isolated from each others. The same XML file which you are setting as a content of each activity doesn't mean that it same/shared instance of layout. You should think not in terms of layouts, but in terms of activities.
In your case you just start second Activity, change background of buttons here, then go back and see first Activity. Any changes in second Activity would not be mirrored somewhere else. That's it.
Try this:
Insert a button to finish in second activity. Use finish() under the button interface button.setOnClickListener(new OnClickListener(){} ); then you'll clearly notice the difference between the backgrounds. Only if you click you can go back to main activity.

Image for ImageButton doesn't change as intended

My goal here is to change an Image from an ImageButton(ibChamp).
package com.example.custombuilds;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;z
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class Champions extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.champions);
ImageButton ibAnnie = (ImageButton) findViewById(R.id.ibAnnie);
ibAnnie.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Check this for errors
RelativeLayout test = (RelativeLayout) findViewById(R.id.layoutChampions);
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.create_build_page, null);
test.addView(view);
ImageButton img = (ImageButton) view.findViewById(R.id.ibChamp);
img.setImageResource(R.drawable.ic_launcher);
try {
Intent open = new Intent("android.intent.action.CREATE");
startActivity(open);
} catch (Exception e) {
}
}
});
}
}
Note that the ImageButton ibChamp is from the xml layout create_build_page, and not the xml champions.
This code runs without crashing, but the Image from the Imagebutton ibChamp does not change, which is what I am trying to do. I will be happy to provide any other additional information.
You are inflating "ibChamp" in onClick. That creates a new ImageButton. You will not see it until you use "addView" from the parent.
You can add your XML, but you need to get a reference to an existing button in Activity in order to change it. Or else add the new button and remove an old one...
In other words, change this:
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.create_build_page, null);
ImageButton img = (ImageButton) view.findViewById(R.id.ibChamp);
to this:
ImageButton img = (ImageButton)findViewById(R.id.ibChamp);
And it will probably do what you want.
you need to call addView() for this inflated view
View view = layoutInflater.inflate(R.layout.create_build_page, null);

dynamic array of LinearLayout

This is a simpler version of something I'm working on. When the add button is pressed, what is supposed to happen is, a LinearLayout is created and a CheckBox is also created with the text within the EditText box. The CheckBox is then placed into the newly created LinearLayout, and the newly created LinearLayout, placed in the already existing LinearLayout(named layout). I know it seems unnecessary to create a new LinearLayout but in the main program, its really important. My problem is, when I run the code, the app 'force closes' so I want to know what it is that I'm doing wrong or if there is a better approach I can take to achieve the result I need.
package co.cc.*******.toDo;
import co.cc.*******.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ToDoMainActivity extends Activity implements View.OnClickListener{
/** Called when the activity is first created. */
Button bAdd,bremove;
EditText et;
// CheckBox cbNew;
LinearLayout layout;//main layout
ArrayList<CheckBox> cbNew;//dynamic array of checkBoxes
ArrayList<LinearLayout> cbLayout;//dynamic array of LinearLayouts
int index = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialize();
bAdd.setOnClickListener(this);
bremove.setOnClickListener(this);
}//end method onCreate
void initialize(){
bAdd = (Button)findViewById(R.id.bAdd);
bremove = (Button)findViewById(R.id.bremove);
et = (EditText)findViewById(R.id.et);
layout = (LinearLayout)findViewById(R.id.layout);
cbNew = new ArrayList<CheckBox>();
}//end method initialize
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.bAdd:
cbLayout.add(index, new LinearLayout(this));//create new layout to store cb
cbNew.add(index, new CheckBox(this));//create new checkbox
cbNew.get(index).setText(et.getText().toString()+ index);//set text to text in editText box
cbLayout.get(index).addView(cbNew.get(index));//add checkbox to newly created layout
layout.addView(cbLayout.get(index));//add newly created layout to already existing layout
index ++;
break;
}//end switch
//layout.removeView(cbNew.get(index));
}//end method onClick
}//end class ToDoMainActivity

Categories