I'm creating a version of the popular Minesweeper game for Android. I'm trying to programmatically create a button and add it to a RelativeLayout. I've found something very similar here: How do I programmatically add buttons into layout one by one in several lines?
When I try to run it I get a NullPointerException at:
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
Here's the whole block of code:
public void create() {
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
for(int i = 0; i < gridSize; i++) {
if(grid[i] == 0) { //if grid pos. indicates an empty cell
Button empty = new Button(this);
empty.setBackgroundResource(R.drawable.emptybutton); //set background to empty
empty.setId(i); //set id to value of i
empty.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout1.addView(empty); //add the button to the relativeLayout view
//((Button) findViewById(i)).setOnClickListener(emptyListener);
}
Thanks in advance for any responses
have set the layout xml of the Activity by setContentView(R.layout.xxxx)?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
...
this
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
should be
RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.relative_id);
R.id... used for mapping control and RelativeLayout is a control.
I think you're getting a blank screen because you haven't set the content view.
What i mean is that the codes does what it's supposed to do however, you should remove the "setContentView()" method at the top and place it at the end, then you should set it to the RelativeLayout before you close the onCreate() method! Something like this:
public void create() {
RelativeLayout layout1 = new RelativeLayout(this);
for(int i = 0; i < gridSize; i++) {
if(grid[i] == 0) { //if grid pos. indicates an empty cell
Button empty = new Button(this);
empty.setBackgroundResource(R.drawable.emptybutton); //set background to empty
empty.setId(i); //set id to value of i
empty.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout1.addView(empty); //add the button to the relativeLayout view
//((Button) findViewById(i)).setOnClickListener(emptyListener);
}
}
setContentView(layout1);
}
Also notice that I've changed the declaration of the Relativelayout a little bit.
I hope this helps. :) !
You must enter the ID of the RelativeLayout, not the xml fil name.
try with
RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.yourRelativeLayoutViewID);
Related
I'm trying to get my button to create a text field where the user can input information. This way they can only create as many lines as they would like. Also, is there a way to create multiple fields at once?
So, it'll end up being something like this:
"Add Event" (rest of the screen is blank until they click on that button)
Text field 1/ Text field 2/ Text field 3
(once they press that button and of course without the underlines, just an example)
So they can put in information that they want there. If they want another row, they click on the add button again.
Am I supposed to be using an onClickListener? I'm confused as to how I would go about making the button create that field for the user.
public class BudgetScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_budget_screen);
Button addBillExpense = (Button) findViewById(R.id.addBillExpense);
addBillExpense.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
TextView inputField = new TextView(BudgetScreen.this);
}
});
}
}
That is what I have so far. I've been stuck on this for a hot minute. I am aware that I haven't used "inputField" yet.
Suppose you have the following layout xml:
<LinearLayout ...>
<Button .../>
<LinearLayout ...
android:id="#+id/holder"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
in button onClickListener you can have something like:
LinearLayout layout = (LinearLayout) findViewById(R.id.holder);
EditText et = new EditText(this);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
layout.addView(et,lp);
You can change the LayoutParams to get the layout you like.
If you want multiple EditText in a single row, you can do the following:
final int NUM_EDITTEXT_PER_ROW = 3;
LinearLayout layout = (LinearLayout) findViewById(R.id.holder);
Display display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth()/NUM_EDITTEXT_PER_ROW;
LinearLayout tempLayout = new LinearLayout(this);
tempLayout.setOrientation(LinearLayout.HORIZONTAL);
for(int i=0;i<NUM_EDITTEXT_PER_ROW;i++){
EditText et = new EditText(this);
LayoutParams lp = new LayoutParams(width,LayoutParams.WRAP_CONTENT);
tempLayout.addView(et,lp);
}
layout.addView(tempLayout);
I want to add an ImageView within the onClick() of the Button. But the ImageView should be aligned to the centre of the button.
How can I do this pragmatically?
I'm creating a new instance of the ImageView to be added on top of the View that called it and it's position is equivalent of the View that called it.
How can I get the X and Y coordinates?
EDIT:
#Override
public void onClick(final View v) {
if(v.getWidth() > v.getHeight()) size = v.getHeight();
if(v.getWidth() < v.getHeight()) size = v.getWidth();
RelativeLayout.LayoutParams button = new RelativeLayout.LayoutParams(size,size);
buttonc = new ImageView(getApplicationContext());
buttonc.setBackgroundResource(R.drawable.round);
layout.addView(buttonc,button);
I'm using the above code to attempt to pragmatically set the size of the ImageView to that of the button, and it's working.
As for the coordinates, I still haven't figured it out.
To add clarity: I'm attempting to create a rounded ripple effect over the view that calls it.
I suggest a better solution create an image view before hand place it in the xml as you see fit,at first set its visibility to false .
On click switch its visibilty to true, and the image will appear
This solution is easier than what you are searching.
Feel free to ask questions
to add Imageview
#Override
public void onClick(final View v) {
//LinearLayout
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
//ImageView
ImageView imageView = new ImageView(this);
//image resource
imageView.setImageResource(R.drawable.specs);
//image position
imageView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
//adding view to layout
linearLayout.addView(imageView);
//make visible to program
setContentView(linearLayout);
}
I'm having a problem with this code. I need to dynamically add buttons to my layout. This code works fine, with one exception. The second button sits on top of the first. This must have something to do with LayoutParams, but I'm not sure what.
private void buttonmaker (Button button)
{
RelativeLayout.LayoutParams rlayout = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rlayout.addRule(RelativeLayout.CENTER_VERTICAL);
rlayout.addRule(RelativeLayout.ALIGN_LEFT);
rlayout.width = 100;
button.setId(Atom.count);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
atoms[id].getname();
TextView textview = (TextView)findViewById(R.id.textView2);
textview.setText(textview.getText()+String.valueOf(atoms[id].getname()));
}
});
if (Atom.count > 1) rlayout.addRule(RelativeLayout.RIGHT_OF,Atom.count-1); else rlayout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
button.setLayoutParams(rlayout);
RelativeLayout v = (RelativeLayout) findViewById(R.id.rlayout);
v.addView(button);
}
the problem is you set de button in the relativelayout, in this component the objects are being added one above the other, you try create linearlayout global with orientation vertical or horizontal depending on what you want and added buttons, and its all
I have this code and i want to add CheckBoxes dynamically inside a LinearLayout that nested inside a ScrollView that nested inside a RelativeLayout( RelativeLayout->ScrollView->LinearLayout->My ChechBoxes)
li = (RelativeLayout) findViewById(R.id.mainlayout);
ScrollView sv = new ScrollView(this);
final LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
li.addView(sv);
sv.addView(ll);
for(int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText("I'm dynamic!");
ll.addView(cb);
}
this.setContentView(sv);
but i get this error:
03-12 20:32:14.840: E/AndroidRuntime(945): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
My RelativeLayout declared in my XML file already
how i can fix this?
this.setContentView(sv);
This tries to add your ScrollView to the FrameLayout android.R.id.content, but you already made li the parent of sv... hence "The specified child already has a parent."
I believe you can remove this.setContentView(sv); since it looks like you only want to add the ScrollView (et al.) to the RelativeLayout, not replace the entire existing layout.
Check this http://developer.android.com/training/animation/screen-slide.html
When you download the sample app, go through LayoutChangesActivity.java
The following is the code to add an item..
private void addItem() {
// Instantiate a new "row" view.
final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(
R.layout.list_item_example, mContainerView, false);
// Set the text in the new row to a random country.
((TextView) newView.findViewById(android.R.id.text1)).setText(
COUNTRIES[(int) (Math.random() * COUNTRIES.length)]);
// Set a click listener for the "X" button in the row that will remove the row.
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Remove the row from its parent (the container view).
// Because mContainerView has android:animateLayoutChanges set to true,
// this removal is automatically animated.
mContainerView.removeView(newView);
// If there are no rows remaining, show the empty view.
if (mContainerView.getChildCount() == 0) {
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
}
});
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
mContainerView.addView(newView, 0);
}
I have ScroolView and it's inside Linear layout. In this linear layout i added programmically around 20 TextView. When i press any of those TextView i change it color to RED (at first it was white). When i press again the same TextView i check his color and if it's is RED i again make it white.
What i want to do:
I press for example 1 TextView and make it RED. Then when i press 2 TextView i make this one RED and i want to make 1 TextView WHITE. This functionality should be at all TextView.
So any idea's how to do this ?
You mean to say at a time you need only one textview to be red. You can do this using 2 variables. One is a boolean colored. This indicates that at least one TextView is colored. Another is a TextView variable. Create a TextView variable lastColoredTextView. Let it be null initially. Then whenever the textview is clicked, assign the lastColoredTextView to the clicked TextView. Then whenever you are clicking, just check if colored then change the color of lastColoredTextView to white.
Change class name and it will work fine.
public class Test_stflowActivity extends Activity {
TextView current_red_txt_box = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = null;
LinearLayout lp = new LinearLayout(getApplicationContext());
lp.setOrientation(LinearLayout.VERTICAL);
View.OnClickListener txt_click = new View.OnClickListener() {
#Override
public void onClick(View v) {
current_red_txt_box.setTextColor(Color.WHITE);
TextView tv = (TextView) v;
tv.setTextColor(Color.RED);
current_red_txt_box = tv;
}
};
for (int i = 0; i < 20; i++) {
tv = new TextView(getApplicationContext());
tv.setId(i);
tv.setTextSize(40);
tv.setText("you text");
tv.setTextColor(Color.WHITE);
tv.setOnClickListener(txt_click);
lp.addView(tv);
current_red_txt_box = tv;
}
setContentView(lp);
}
}